userMod2
userMod2

Reputation: 8960

Regex for month and day before specific symbols

I'm trying to get the day and month from strings such as:

5月2日 or 4月22日 or 12月2日

However I can't see to figure out the correct regex:

I've tried \d{1,2}[^月] and \d{1,2}[^日] however this only returns something if there is a double digit in the day or month.

Any ideas what I'm missing?

Thanks.

Upvotes: 0

Views: 33

Answers (2)

JacaByte
JacaByte

Reputation: 335

Assuming you have 12 months per year and up to 31 days per month this will get you close, you'll still have to do bounds checking after you determine the syntax is correct; (read; month 19 day 37 will be valid syntax here)

1?\d月[123]?\d日

Edit: Here's a better regex that doesn't need to be bounds checked and doesn't require lookahead;

^(1[012]|[1-9])月(3[01]|[12]\d|[1-9])日$

Upvotes: 0

ctwheels
ctwheels

Reputation: 22817

\d{1,2} is matching 1 digit and [^月] is matching another. Your current regex will match two digits and then any character except

The correct way to ensure the follows is to use a lookahead \d{1,2}(?=月) as seen in use here

Upvotes: 1

Related Questions