简体   繁体   中英

Regex Group Optional

I have the following regular expression that isn't working the way I thought it would.

("^\\d{2}(?:\\d{2})?\\.\\d{2}(\\.\\d{2-4})?$");

I am trying to match a string that starts with either 2 or 4 digits, followed by a period, followed by 2 digits and then optionally another period and either 2 or 4 digits.

I would expect 33.44.4444 to work, as would 33.33 but anytime I have a string that has a 2nd period, my expression fails.

What am I doing wrong ?

Your regex is correct for what you want to do except for the {2-4} part, if you use {2,4} it will go for the 2 to 4 characters capture you're looking for.

("^\\d{2}(?:\\d{2})?\\.\\d{2}(\\.\\d{2,4})?$");

Hope it helps.

As others have pointed out the syntax {2-4} is incorrect. Use {2,4} to specify a range of occurrences. But also if you only want 2 or 4 (not 3) I would use this regex:

@"^(\d{2}|\d{4})\.\d{2}(\.(\d{2}|\d{4}))?$"

You can use this regex:

^\d{2}(?:\d{2})?\.\d{2}(?:\.\d{2}(?:\d{2})?)?$

\\d{2-4} will match {2-4} text literally.

RegEx Demo

The way you expressed "either two or four digits" in the first section of your expression is correct:

\\d{2}(?:\\d{2})?

The second part does it incorrectly:

(\\.\\d{2-4})?

Copy the first part into the second to fix the problem:

("^\\d{2}(?:\\d{2})?\\.\\d{2}(\\.\\d{2}(?:\\d{2})?)?$");

Demo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM