2016-06-09 70 views
0

我想匹配通過正則表達式解析字符串。這是我到目前爲止有:正則表達式困擾和正確解析字符串

private string result = @"Range:\s*(?<start>.+\S)\s*to\s*(?<end>.+\S)[\S\s]+For more information, click the link below"; 

和代碼解析:

start = Convert.ToDateTime(matches.Groups["start"].Value) 
end = Convert.ToDateTime(matches.Groups["end"].Value) 

下面是一個例子字符串輸入:

範圍:2016年6月8日至2016年6月9日
欲瞭解更多信息,請點擊下面的鏈接

start變量是如下預期:

2016年6月8日12:00:00 AM

end變量被格式化爲DateTime引發錯誤。當我輸出end正則表達式匹配的值,它出來是這樣的:

2016年6月9日更多的Infor .....

什麼我在我的正則表達式失蹤?

回答

0

你將不得不如果文本For more information, click the link below不會出現在您所描述的結果一條單獨的線。

如果換行符不符合日期,則.+將消耗所有字符,直到下一個換行符爲止,該換行符只與\s一致。這是因爲+是貪婪的。爲了讓它變懶,請添加問號。因爲是懶,你並不真的需要捕獲組內的\S

Range:\s*(.+?)\s*to\s*(.+?)\s*For more information, click the link below 
1

使用此模式:

@"Range:(?<start>\w+ \d+, \d+) to (?<end>\w+ \d+, \d+)" 

以防萬一,你需要配合第2部分:

@"Range:(?<start>\w+ \d+, \d+) to (?<end>\w+ \d+, \d+)\r\nFor more information, click the link below"; 
0

嘗試this網站。它產生的正則表達式有點長,但它對我來說很有用。