简体   繁体   中英

Regular expression pattern for dates with different symbols and variable digit formats

I am trying to parse out some dates in a text field that could be in the following formats (note the text field has a bunch of other junk surrounding the dates):

//with dashes
10-10-16
1-5-16
10-1-16
1-10-16

//with periods
10.10.16
1.5.16
10.1.16
1.10.16

//with forward slashes
10/10/16
1/5/16
10/1/16
1/10/16

What I need is one pattern for all digit format scenarios. Here is what I tried:

//x.xx.xx
Regex reg1 = new Regex (@"\(?\d{1}\)?[-/.]? *\d{2}[-/.]? *[-/.]?\d{2}")

//xx.xx.xx
Regex reg2 = new Regex (@"\(?\d{2}\)?[-/.]? *\d{2}[-/.]? *[-/.]?\d{2}")

//x.x.xx
Regex reg3 = new Regex (@"\(?\d{1}\)?[-/.]? *\d{1}[-/.]? *[-/.]?\d{2}")

//xx.x.xx
Regex reg4 = new Regex (@"\(?\d{2}\)?[-/.]? *\d{1}[-/.]? *[-/.]?\d{2}")

I'm new to regular expressions, so I am looking for a single expression that will handle all these scenarios (ie., digit formats with single number and double digit numbers for -/. in between).

Is there one expression that could handle this?

Thanks,

I can suggest

Regex rx = new Regex(@"\(?(?<!\d)\d{1,2}\)?[-/.]?\d{1,2}[-/.]?\d{2}(?!\d)");

If your date separators are used consistently, use the backreference with a capturing group:

Regex rx = new Regex(@"\(?(?<!\d)\d{1,2}\)?([-/.])\d{1,2}\1\d{2}(?!\d)");

See the regex demo 1 and demo 2 .

Details :

  • \\(? - an optional (
  • (?<!\\d) - there must be no digit before the current location
  • \\d{1,2} - 1 or 2 digits
  • \\)? - an optional )
  • [-/.]? - an optional - , / , or .
  • \\d{1,2}[-/.]? - ibid.
  • \\d{2} - 2 digits
  • (?!\\d) - there must be no digit after the current location.

The version with a capturing group/backreference contains ([-/.]) - a capturing group with ID=1 that matches the first separator, and \\1 is the backreference that matches the same text captured into Group 1 (making the second separator to be identical to the first one).

You can also try this: \\d{1,2}([-./])\\d{1,2}\\1\\d{2}

Regex regex = new Regex(@"\\d{1,2}([-./])\\d{1,2}\\1\\d{2}");

  • \\d{1,2} between one and two digits
  • ([-./]) any of . , - and /
  • \\1 repeat this character another time to (prevent matching 1.1/01 or 1-1.01 )
  • \\d{2} matches two digits

尝试这个

\d{1,2}(-|\.|\/)\d{1,2}(-|\.|\/)\d{1,2}

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