我應該:
- 檢查創建的檔案是否存在
- 讀取預制文本檔案中的內容,只提取日期
- 計算匹配的數量
文本檔案名為:test.txt,包含以下資訊:
22 Jan,
Hello,
983shs247,
^*(26308,
27 December,
This is a test,
19 June.
輸出應該是:
Date Match,
Please enter file name: test.txt,
File exists!,
The date found is: 22 Jan,
The date found is: 27 December,
The date found is: 19 June,
The number of match is: 3.
我的代碼只顯示到“日期匹配,請輸入檔案名:test.txt,檔案存在!,匹配數為:0。我的正則運算式似乎沒有提取日期。請協助
Console.WriteLine("Date Match");
Console.Write("Please enter the file name: ");
string filename = Console.ReadLine();
string fullname = @"C:\Work\" filename;
int counter = 0;
if (File.Exists(fullname))
{
Console.WriteLine("File exists!");
StreamReader file3 = new StreamReader(fullname);
String inputdata;
Regex pattern1 = new Regex(@"\d{2}\s [Jan | Feb | Mar | Apr | May | June | Jul | Aug | Sep | Oct | Nov | December]");
while ((inputdata = file3.ReadLine()) != null)
{
foreach(Match m in pattern1.Matches(inputdata))
{
Console.WriteLine("The date found is :" inputdata);
counter ;
}
}
Console.WriteLine("The number of match is :" counter);
file3.Close();
}
Console.ReadLine();
uj5u.com熱心網友回復:
你的正則運算式是錯誤的。嘗試:
Regex pattern1 = new Regex(@"\d{1,2}\s (?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?|July?|Aug(?:ust)?|Sept?(?:ember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember))");
正則運算式語言 - 快速參考
uj5u.com熱心網友回復:
我建議決議- DateTime.TryParseExact- 而不是正則運算式匹配,例如
using System.Globalization;
using System.IO;
using System.Linq;
...
Console.WriteLine("Date Match");
Console.Write("Please enter the file name: ");
string filename = Console.ReadLine();
string fullname = Path.Combine(@"C:\Work", filename);
// Let's get rid of streams and query the file:
var counter = File
.ReadLines(fullname)
.Count(line => DateTime.TryParseExact(
line.Trim(' ', '.', ','),
new string[] { "d MMM", "d MMMM"},
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal,
out var date));
Console.WriteLine($"The number of match is {counter}");
請注意:
- 決議不匹配錯誤的“日期”,如
30 Feb - 這是很容易的添加新的格式,例如
MMM d用于APR 30 - 如果您想本地化例程(例如讓它說俄語),您所要做的就是指定文化:
CultureInfo.GetCulture("ru-Ru")而不是開發新的正則運算式模式
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/365677.html
標籤:C#
上一篇:通過替代方法將OpenJDK切換到java-1.8.0-openjdk失敗!/usr/bin可能不存在或指向不同的java版本
