DD
DevDash

Regex for Localhost Detection

Regex Pattern

^(?:https?:\/\/)?(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/.*)?$

Detects localhost URLs (localhost, 127.0.0.1, ::1)

Quick Answer

The regex pattern for localhost detection is `^(?:https?:\/\/)?(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/.*)?$`. Detects localhost URLs (localhost, 127.0.0.1, ::1). This works in JavaScript, Python, Ruby, PHP, Java, and most regex engines that support PCRE syntax.

Test Examples

InputResult
http://localhost:3000✓ Matches
https://127.0.0.1✓ Matches
localhost:8080/api✓ Matches
http://example.com✗ No match
192.168.1.1✗ No match
http://local.host✗ No match

Code Examples

javascript

const regex = /^(?:https?:\\/\\/)?(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:\\/.*)?$/;
const isValid = regex.test(value);

python

import re
pattern = r'^(?:https?:\/\/)?(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/.*)?$'
if re.match(pattern, value):
    print("valid")

ruby

pattern = /^(?:https?:\/\/)?(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:\/.*)?$/
if value =~ pattern
  puts "valid"
end

php

if (preg_match('/^(?:https?:\\/\\/)?(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:\\/.*)?$/', $value)) {
    echo "valid";
}

java

String pattern = "^(?:https?:\\/\\/)?(?:localhost|127\\.0\\.0\\.1|\\[::1\\])(?::\\d+)?(?:\\/.*)?$";
boolean isValid = value.matches(pattern);

Frequently Asked Questions

Related Regex Patterns

Want API access + no ads? Pro coming soon.