Regex for Port Number
Regex Pattern
:([0-9]{1,5})(?:\/|$)Extracts port number from a URL or host string
Quick Answer
The regex pattern for port number is `:([0-9]{1,5})(?:\/|$)`. Extracts port number from a URL or host string. This works in JavaScript, Python, Ruby, PHP, Java, and most regex engines that support PCRE syntax.
Test Examples
| Input | Result |
|---|---|
| localhost:3000 | ✓ Matches |
| http://example.com:8080/path | ✓ Matches |
| 192.168.1.1:443 | ✓ Matches |
| example.com | ✗ No match |
| http://example.com | ✗ No match |
| localhost | ✗ No match |
Code Examples
javascript
const regex = /:([0-9]{1,5})(?:\\/|$)/;
const isValid = regex.test(value);python
import re
pattern = r':([0-9]{1,5})(?:\/|$)'
if re.match(pattern, value):
print("valid")ruby
pattern = /:([0-9]{1,5})(?:\/|$)/
if value =~ pattern
puts "valid"
endphp
if (preg_match('/:([0-9]{1,5})(?:\\/|$)/', $value)) {
echo "valid";
}java
String pattern = ":([0-9]{1,5})(?:\\/|$)";
boolean isValid = value.matches(pattern);Frequently Asked Questions
Related Regex Patterns
Subdomain Extraction
Extracts the subdomain from a URL or domain name
Protocol Detection
Detects and captures the protocol from a URL
Query Parameter
Extracts key-value pairs from URL query strings
HTTP vs HTTPS URL
Matches HTTP or HTTPS URLs and captures the protocol
Data URL
Matches data: URL scheme with optional MIME type and base64 encoding
WebSocket URL
WebSocket URL starting with ws:// or wss://