2016-06-09 122 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网站。它产生的正则表达式有点长,但它对我来说很有用。