我试着为日期制作正则表达式,所以请建议正确的方法

时间:2015-08-09 03:17:56

标签: c# regex

我试着制作符合这种格式的正则表达式,例如" 12-apr"或" 23 jun"或继续像Jan,feb,Mar一样整月,...... Dec。

在此正则表达式中,前两位数始终为数字,最后3位数仅从12月开始,如jan ...至Dec.and前两位数不超过31。

此时正则表达式格式包含" 12-Apr" " 12 /月" " 12 /月"所以我们需要正则表达式通过上述所有条件。

字符串是这样的"你好12 /可能789"所以从这个我想只有12 / may是因为我做下面的正则表达式。

也有可能"你好12 / xyz 789"所以这次正则表达式与任何东西都不匹配,因为xyz donot与jan到Dec的任何月份格式匹配。

所以也需要通过这个条件。

我尝试\ b((0?[1-9] | [12] \ d | 3 [01])[.- \]?[a-zA-Z] {3})\ b这个问题的正则表达式,但是当字符串是"你好12 /可能789"时传递所有条件。也会返回12 /月。

但不满足我的正则表达式,当字符串是"你好12 / xyz 789"我的字符串也匹配12 / xyz并返回该值。

所以可以使用正则表达式解决我的问题吗?

3 个答案:

答案 0 :(得分:1)

只需将[A-Za-z]{3}替换为jan|feb|mar|....|dec

即可
@"(?i)\b((0?[1-9]|[12]\d|3[01])[ \\.-/]?(jan|feb|mar|apr|may|ju[ln]|aug|sep|oct|nov|dec))\b"

但请注意,我可以修改到2月份最多28天,但正则表达式不会计入闰年。所以不要用正则表达式来解析日期。

答案 1 :(得分:0)

Trt this one

/\b(?:0[\d]|1[\d]|2[\d]|30|31)+(?: |-|\/)(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/gim

答案 2 :(得分:0)

您可以使用DateTime.TryParseExact通过拆分输入字符串来解析“dd / MMM”和“dd-MMM”格式的日期。

对于feb,它不会允许大于31和29的日期,而对于其他月份则不会。

如果您提供年份,您可以考虑闰年,否则将考虑当年。

对于月份,它将使用“MMM”作为月份的缩写,如果你想考虑整个月份的月份,你可以使用“MMMM”(带有pattern3和else if条件)。

using System;
using System.Globalization;

namespace MyCOnsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string pattern1 = "dd/MMM";
            string pattern2 = "dd-MMM";
            DateTime parsedDate;
            string input = "hello 12/May 789";//your string
            string[] results = input.Split(new string[] { " " }, StringSplitOptions.None);

            foreach (var result in results)
            {
                //pattern1
                if (DateTime.TryParseExact(result, pattern1, CultureInfo.InvariantCulture,
                                          DateTimeStyles.None, out parsedDate))
                    Console.WriteLine("Converted '{0}' to {1:d} by pattern1.",
                                      result, parsedDate);
                //pattern2
                else if (DateTime.TryParseExact(result, pattern2, CultureInfo.InvariantCulture,
                                      DateTimeStyles.None, out parsedDate))
                    Console.WriteLine("Converted '{0}' to {1:d} by pattern2.",
                                      result, parsedDate);
                else
                    Console.WriteLine("Unable to convert '{0}' to a date and time.",
                                      result);
            }

            //splitted values
            foreach (string s in results)
                Console.WriteLine(s);

            Console.ReadLine();

        }
    }
}

更多关于:
Custom date and Time string formats

注意:我没有使用正则表达式。但这是解决问题的另一个简单选择。