开发者

How do I check for multiple date formats in Regex?

开发者 https://www.devze.com 2023-01-29 21:03 出处:网络
I am looking in a string to pull 2 date values in the format mm/dd/yyyy, m/d/yyyy, 开发者_运维知识库m/dd/yyyy, or mm/d/yyyy.How do I add that condition to my Regex?

I am looking in a string to pull 2 date values in the format mm/dd/yyyy, m/d/yyyy, 开发者_运维知识库m/dd/yyyy, or mm/d/yyyy. How do I add that condition to my Regex?

private static readonly Regex dateRegex = new Regex(@"\d{2}/\d{2}/\d{4}");


private static readonly Regex dateRegex = new Regex(@"\d{1,2}/\d{1,2}/\d{4}");

Edit: After obtaining initial matches, attempt to parse them using DateTime.TryParse to verify that they are indeed valid dates. Otherwise your regex will need to be significantly more complex (see Jeff the Bear's answer).


This will do the job:

\d{1,2}\/\d{1,2}\/\d{4}


With an "OR". In Regex "|":

"(regex1 | regex2)"

like:

Regex dateRegex = new Regex(@"(\d{1,2}/\d{1,2}/\d{4}|\d{1,2}\.d{1,2}\.d{1,4})");


Use a regex like this (option1|option2)

The | is an OR.

BUT reading your examples, I don't think you need it. Try this instead.

(?<month>[0-9]{1,2})\/(?<day>[0-9]{1,2})\/(?<year>[0-9]{4})

In the {n,m} clause, n is the minimum number that must be matched while m is the maximum number.

NOTE: there's a comment on a post around here somewhere that talks about using [0-9] instead of \d since \d can also match some unicode characters.

0

精彩评论

暂无评论...
验证码 换一张
取 消