0

I need to allow an IP/DNS name from a text box. I am looking for a IP regular expression which work for IP.

Now I am using one regular expression:

/\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/

which was working for 0-255 range. But allowing invalid IP such as : 121.21.05.234.01 which has 5 parts.

I need a regular expression which will work in all scenario's like below:

10.2.22.1        - true
123.123.123.123  - true
123.123.023.12   - true
12.23.12.0       - true
121.21.05.234.01 - false

Please provide me DNS expression also.

Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
user1952461
  • 41
  • 1
  • 5
  • The `\b` in your pattern match on word-boundaries, which are the (effectively) empty spaces between `a-zA-Z0-9_` and anything not those characters. The dot for the 5th octet qualifies as "anything not those", which is why your pattern still matches. See sp00m's answer. – Kenneth K. Mar 18 '13 at 13:16

2 Answers2

0

Try to anchor your regex with ^ and $, which will make it match the whole string.

sp00m
  • 47,968
  • 31
  • 142
  • 252
0

Are you looking for a way to specify an occurrence count? You may achieve this with curly brackets. An exemple here.

In your case, it would lead to:

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

(I added a \ to escape the dot, too)

Community
  • 1
  • 1
Vincent
  • 1,035
  • 6
  • 14