-2

I have below host name and i want regex for the same

127.0.0.1:8181

The input contains numbers, dot(.) and colon (:)

I used below regex, but none of them worked

^([0-9]|#|+|*)+$
^[0-9*#+]+$

Adding my code snippet below

var guidRegex = new RegExp("/[0-9.:]+/")
var hostName = "127.0.0.1:8181";
var match = guidRegex.test(hostName);

After executing the value of match is FALSE

Ajithesh Gupta
  • 87
  • 2
  • 13
  • See for example https://stackoverflow.com/questions/34438566/regex-pulling-ip-and-port-from-string or https://stackoverflow.com/questions/2908740/java-regex-matching-ip-address-and-port-number-as-captured-groups or https://stackoverflow.com/questions/23542035/how-to-modify-regular-expression-for-ipport – The fourth bird Apr 13 '20 at 07:04

2 Answers2

1

Try:

^\d+(?:\.\d+){3}(?::\d+)?$

Demo

This will match an IPv4 address, along with an optional port number appearing at the end.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

To validate a string with numbers . and :.

let str = '127.0.0.1:8181';
console.log(/[0-9.:]+/g.test(str));

To validate IPV4 ips addresses:

let str = '127.0.0.1:8181';
console.log(/[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}:([0-9]+)?/g.test(str));

//OR

console.log(/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}(:[0-9]+)?$/g.test(str));
Sohail Ashraf
  • 10,078
  • 2
  • 26
  • 42