1

I am writing a regex to recognize IP address of the form "A.B.C.D", where the value of A, B, C, and D may range from 0 to 255. Leading zeros are allowed. The length of A, B, C, or D can't be greater than 3. I know this regex is easily available on Internet but I am writing it on my own for practice.

First I wrote the regex for A as follows:

a = ^(^0{0,2}\d|^0{0,1}\d\d|[0-1]\d\d|2[0-4]\d|25[0-5])$

It works as expected, then I wrote it for A.B as follows:

ab = ^(^0{0,2}\d|^0{0,1}\d\d|[0-1]\d\d|2[0-4]\d|25[0-5])\.
      (^0{0,2}\d|^0{0,1}\d\d|[0-1]\d\d|2[0-4]\d|25[0-5])$

But somehow it isn't working as expected. It's not recognizing strings like "2.3" but recognizing "2.003". This is very weird. I have spent hours figuring it out but have totally given up now. Please help me with this.

4
  • 4
    Makes no sense ^ inside the parenthesis as it already exists one outside it. Commented Apr 16, 2017 at 5:50
  • 4
    And it is exactly what is causing your problem: regex101.com/r/9FtLe1/1 Commented Apr 16, 2017 at 5:58
  • I am so sorry for being such a idiot. Yes that solved the problem. I was experimenting putting ^ and $ and outside and then forget to remove them. Ah! Very stupid of me. Commented Apr 16, 2017 at 6:03
  • 3
    Hey, we all have those moments. You'd have been an idiot not to ask for help. Happy coding! Commented Apr 16, 2017 at 6:06

1 Answer 1

2

As @Jorge pointed out in the comments, the ^ character matches the start of a string/line, which can occur for A, as it is presumably the first group of characters in the line, but cannot occur for B, since it will always be preceded by A. This is why it could match 003 (through the subpattern [0-1]\d\d), but it couldn't match 3 through the subpattern ^0{0,2}\d.

Remove the superfluous ^s, and you should get the desired behavior:

ab = ^(0{0,2}\d|0{0,1}\d\d|[0-1]\d\d|2[0-4]\d|25[0-5])\.
      (0{0,2}\d|0{0,1}\d\d|[0-1]\d\d|2[0-4]\d|25[0-5])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.