2016-03-26 143 views
-1

我正在處理一個C#項目,我需要解析並從某些字符串中提取一些日期。 Theese是我的字符串:從字符串中提取日期的正則表達式

裝飾板礦石19.30德爾2016年4月2日全部礦石19.30德爾2016年6月2日
裝飾板礦石19.30德爾2016年6月2日全部礦石19.30德爾2016年8月2日
...

對於每一個我想提取兩個日期(例如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解決

try代碼是好的,但問題是,HH.mm和日期之間可能有幾個空格和字符。幾次是以這種形式:HH:mm del dd.MM.YYYY但有時以這種格式dd.MM.YYYY del       dd.MM.YYYY。你認爲仍然有可能用一個正則表達式解析所有數據,還是必須標記字符串?非常感謝你!

+0

如果日期格式是**確實是**固定的(DD.MM.YYYY),您可以使用'Regex rgx = new Regex(@「\ d {1,2} \。\ d { (請注意,您必須轉義'\ .',否則它是一個'.',它可以匹配linebreaks以外的所有內容(http://regexr.com/3d3fv ) –

+0

要小心,如果它的語言環境依賴 - 比正則表達式拋出窗口!MM/DD/YYYY,YYYY-MM-DD,甚至MM.DD.YYYY。你正在設置自己的頭痛。如果你100%確定並確信它始終是固定的日期格式,那麼就依靠它吧。 – t0mm13b

+0

你的意思是你需要一個代碼來獲得多個匹配嗎?你的正則表達式[匹配所有日期](https://regex101.com/r/qB6sT9/1)。 –

回答

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。