RE2 failed to match easy pattern

78 views Asked by At

Using simple regexp with re2j library with Spring (Java) project. In debug mode I found out that pattern:

^[0-9a-fA-F:]+$

It compiled, but failed to recognize text:

123ABC:DEF456
0:1:2:3:4:5
12345
90210-1234

Expecting that pattern matched text, but hasMatch = false

2

There are 2 answers

4
Tim Biegeleisen On

I see multiple problems with your current pattern. First, it appears that the separator character could be either : or -, but your pattern only caters to the former. Also, if you want to match many such strings across multiple lines, then you need to take that into account.

Try this version:

^[0-9a-fA-F]+(?:[:-][0-9a-fA-F]+)*(?:\r?\n[0-9a-fA-F]+(?:[:-][0-9a-fA-F]+)*)*$

Demo

If you only need to match one line at time, then simplify to:

^[0-9a-fA-F]+(?:[:-][0-9a-fA-F]+)*$
0
RUSLAN SIMAKOV On

Thank you to @Wiktor Stribiżew's comment:

Missed the MULTILINE flag? (?m)^[0-9a-fA-F:]+$

This solved the issue:

Pattern.compile(regEx, Pattern.MULTILINE)