Hooli
Hooli

Reputation: 731

How to repeat a capturing group?

I am trying to write a regex for validating an IP address.

While this works:

String reg = "((0|1)?\\d{1,2}|2[0-4]\\d|25[0-5])";
public String pattern = reg + "." + reg + "." + reg + "." + reg;

This doesn't seem to work and I don't understand what is wrong.

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

Please explain what am I missing.

Upvotes: 3

Views: 114

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726539

You are not grouping correctly: the dot \\. is part of the 25[0-5] production, so it wouldn't be matched in the middle of your three-part group unless the address consists exclusively of 25x components.

Your first regex is free from this problem because dots are added outside the grouping parentheses. However, the dots are not escaped, meaning that the expression would match some incorrect strings along with the correct ones (e.g. 123a210b132c210)

Adding parentheses around your digit productions fixes this problem:

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

Demo.

Upvotes: 4

Related Questions