TokyoMike
TokyoMike

Reputation: 828

How to match unspecified number of digits between negative lookbehind and positive lookahead

I am trying to create a regex which matches the digits in the following Japanese strings,

4日   
12日

while ignoring the following strings completely.

3月01日
3月1日
3月31日

So far, the closest I have been able to get is by using:

(?<!月)([0-9]{1,2})(?=日)

but this ends up matching the "1" contained in 3月01日 and 3月31日. Any suggestions?

Upvotes: 1

Views: 934

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626903

Add a digit pattern to the lookbehind:

(?<![0-9月])([0-9]{1,2})(?=日)
     ^^^

See the regex demo

The (?<![0-9月]) lookbehind will fail all the matches when the current position is preceded with a digit or and backtracking won't return the partial numbers in the unwanted context.

Upvotes: 1

Related Questions