繁体   English   中英

正则表达式出现问题并正确解析字符串

[英]Regex woes and parsing a string correctly

我试图匹配通过正则表达式解析字符串。 这是我到目前为止的内容:

 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

end变量在格式化为DateTime引发错误。 当我输出end正则表达式匹配的值时,结果如下所示:

2016年6月9日有关更多信息.....

我的正则表达式中缺少什么?

使用此模式:

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

以防万一,您需要匹配第二部分:

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

如果文本For more information, click the link below没有出现在单独的行上” For more information, click the link below则您将得到描述的结果。

如果换行符不在日期之后,则.+将消耗所有字符,直到下一个换行符为止,下一个换行符只能由\\s与字符串匹配。 这是因为+是贪婪的。 要使其变得懒惰,请添加问号。 因为它很懒,所以您实际上不需要捕获组中的\\S

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

试试这个网站。 它生成的正则表达式有点长,但是对我有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM