Search code examples
javascripthtmlregexportip-address

Regex for ip addres v4 with optional port


I had problem to detect input with pattern for ip address v4 with optional port

I had found just pattern for ip address v4 only

this is code only for ipv4

/\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\b/

i'd expected regex can read, example: 192.168.11.11 or 192.168.11.11:8000


Solution

  • As it stands, your regex will match the IP address. If you also want it to match the port, just add in a optional non-capturing before the final word boundary to pick up : followed by 0-4 digits:

    (?::\d{0,4})?\b
    

    This would create the following:

    /\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)(?::\d{0,4})?\b/
    

    Which matches both of your inputs:

    const regex = /\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)(?::\d{0,4})?\b/;
    
    console.log(regex.test('192.168.11.11'));
    console.log(regex.test('192.168.11.11:8000'));