0

This regex is used to validate ip address

regex = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"

/!\ modified version /!\

regex = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.(\\1)\\.(\\1)\\.(\\1)$"

But the modified version is not working!! why it is not working??

5
  • 3
    Define "not working". Also \\1 expects exact same value as matched by group 1, so in case of regex like ([a-c])\\1 it can match only aa bb cc, not ac since group 1 would hold a in this case. Commented Jun 1, 2015 at 22:44
  • not working == its not vaildating it correclty :D Commented Jun 1, 2015 at 22:47
  • In that case what do you mean by "correctly"? :) Commented Jun 1, 2015 at 22:48
  • if i give input = 000.12.12.034 , the regex is returning false.. but it should return true. Commented Jun 1, 2015 at 22:49
  • 1
    I understand what you are trying to do, it's not possible with java regex since it has not the feature to reuse sub-patterns. But keep in mind that the assertion "a shorter pattern is faster" is totally false. Commented Jun 1, 2015 at 23:11

1 Answer 1

2

\\1 expects exact same value as matched by group 1, so your regex can find only IPs like

123.123.123.123 

since first element is stored in group 1 and rest of elements needs to match it.

What you seem to be looking for is limited repetitions {n} like

String regex = "([01]?\\d\\d?|2[0-4]\\d|25[0-5])(\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])){3}";

BTW I skipped ^ and $ flags since matches(regex) adds them by default, and if you want to use matcher.find() then you probably don't need them since you are probably looking for IP inside some text.

Sign up to request clarification or add additional context in comments.

3 Comments

i tried your regex but its giving me an error can't find symbol ([01]?\\d\\d?|2[0-4]\\d|25[0-5])(\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])){3} and the up arrow pointing at the 25[0-5]
@syed_sami How exactly are you using this regex? Did you used it as String?
i'm using it as a string.. just like this String ip = (my input here); System.out.println(ip.matches(regex));

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.