[英]Using regex to find date string in file
我需要在文本文件中找到特定的日期字符串。 文件中當前有兩個日期字符串-“到期日期:01/26/2016”和“日期:01/252016”。 我需要找到第二個,但是我當前的代碼只能找到第一個。 我猜正則表達式將是一個更好的實現,但不確定如何為其編寫代碼。
當前代碼-
searchString = "Date:";
if (fileContents.IndexOf(searchString) > 0)
{
string tmp = fileContents.Substring(fileContents.IndexOf(searchString) + searchString.Length).Trim();
string loan_date = tmp.Substring(0, tmp.IndexOf('\r')).Trim();
if (loan_date.Count(x => x == '/') == 1)
{
StringBuilder sb = new StringBuilder(loan_date);
sb[sb.Length - 4] = '/';
loan_date = sb.ToString();
}
DateTime dt = DateTime.ParseExact(loan_date, "M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture);
return dt;
}
在C#中,您可以通過執行以下操作找到與正則表達式的匹配項。
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = "[0-1]?[0-9]/[0-9]{2}/[0-9]{4}";
string input = "Due Date: 01/26/2016 Date: 01/25/2016";
foreach (var m in Regex.Matches(input, pattern)) {
Console.WriteLine("'{0}' found at index {1}.",
m.Value, m.Index);
}
}
}
該正則表達式特別表示0或1(可選),后跟一個數字,后跟一個斜杠,然后是兩個數字,然后是一個斜杠,然后是四個數字。
我還假設您的第二個約會01/252016包含錯字。
試試這個正則表達式:
(Due\s)?(Date:)\s([0-1][0-2])\/([0-3][0-9])\/([0-2][0-9]{3})
由於兩個字符串都包含“日期”,因此我們可以使用它進一步過濾掉其他字符串(您可能實際上並不需要所有日期)。 由於Due是可選的,因此我們可以將其標記為。 過濾掉格式不正確的日期有些困難,但是您可以限制一些事情(例如我上面提到的)。 您必須單獨確認日期才能確定。
這是一個正則表達式,只要格式正確,它就不會關心檢查:
(Due\s)?(Date:)\s([0-9]{2})\/([0-9]{2})\/([0-9]{4})
或者只是日期:
([0-9]{2})\/([0-9]{2})\/([0-9]{4})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.