Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to capture 2 consecutive digits, but don't capture if 3 or more

Tags:

java

regex

For example. If I have 1234X03.04

I want to capture the 03 and 04 But I don't want 12, 23, 34

I understand:

  • negative lookahead: (?!...)
  • negative lookbehind: (?<!...)

But, I don't know how to combine that into a single regex. Can someone help me out? Cheers.

like image 943
JGFMK Avatar asked Nov 30 '25 16:11

JGFMK


1 Answers

You can use:

(?<!\d)\d{2}(?!\d)
  • (?<!\d) - prior char is not a digit
  • \d{2} - exactly two consecutive digits
  • (?!\d) - next char is not a digit

Here's a demo of the results in PHP. I think PHP's regex is close to Java's.

like image 135
MonkeyZeus Avatar answered Dec 02 '25 06:12

MonkeyZeus