Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repeat a capturing group?

Tags:

java

regex

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.

like image 871
Hooli Avatar asked Apr 16 '26 06:04

Hooli


1 Answers

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.

like image 125
Sergey Kalinichenko Avatar answered Apr 17 '26 20:04

Sergey Kalinichenko