正则表达式从字符串

时间:2016-03-26 12:58:04

标签: c# regex

我正在开发一个C#项目,我需要从一些字符串中解析并提取一些日期。 Theese是我的字符串:

  

dalle ore 19.30 del 04.02.2016 alle ore 19.30 del 06.02.2016
  dalle ore 19.30 del 06.02.2016 alle ore 19.30 del 08.02.2016   
...

对于每一个我想提取两个日期(例如04.02.2016 06.02.2016)并保存为两个变量。接下来,我将解析它们以创建两个DateTime对象。 现在我正在使用这段代码:

 public static string isdate(string input)
 {
  Regex rgx = new Regex(@"\d{2}.\d{2}.\d{4}");
  Match mat = rgx.Match(input);
  if(mat.Success)
  return mat.ToString();
  else return null;
 }

使用此代码,我可以提取第一个日期而不是第二个日期。我怎样才能改进正则表达式? 谢谢!

尝试以下代码

        static void Main(string[] args)
        {
            string[] inputs = {
                 "dalle ore 19.30 del 04.02.2016 alle ore 19.30 del 06.02.2016", 
                 "dalle ore 19.30 del 06.02.2016 alle ore 19.30 del 08.02.2016"
                             };

            string pattern = @"(?'hour'\d\d).(?'minute'\d\d)\sdel\s(?'day'\d\d.\d\d.\d\d\d\d)";

            foreach (string input in inputs)
            {
                MatchCollection matches = Regex.Matches(input, pattern);
                foreach (Match match in matches)
                {
                    TimeSpan time = new TimeSpan(int.Parse(match.Groups["hour"].Value), int.Parse(match.Groups["minute"].Value), 0);
                    DateTime date = DateTime.ParseExact(match.Groups["day"].Value, "MM.dd.yyyy", CultureInfo.InvariantCulture);

                    Console.WriteLine("Time : {0}", date.Add(time));
                }
            }
            Console.ReadLine();
        }

好的jdwend的解决方案很好,但问题是在HH.mm和日期之间可能有几个空格和字符。有几次是这种形式:HH:mm del dd.MM.YYYY但有时也是这种形式dd.MM.YYYY del dd.MM.YYYY。您是否仍然可以使用一个正则表达式解析所有数据,还是必须对字符串进行标记化?非常感谢你!

1 个答案:

答案 0 :(得分:0)

您的正则表达式没问题,但您只检索第一个匹配。要获取所有匹配项,请使用Matches代替Match

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

public static IEnumerable<string> ExtractDates(string input)
{
     return from m in dateRegex.Matches(input).Cast<Match>()
            select m.Value.ToString();
}

注意:

  • 由于Regex对象是线程安全且不可变的,因此您不需要每次都重建它。您可以将其安全地存储在静态变量中。

  • 由于Matches方法早于.NET泛型,我们需要Cast<Match>调用将结果集合强制转换为IEnumerable<Match>,以便我们可以使用LINQ。< / p>