给定以下示例,我们如何将其解析为可能包含/可能不包含其他短语的组?
我们需要的是:
(Text: any number of words) (LocationIndicator: 0 or 1 @) (Location: any number of words)示例:
"meet me @home":
<Text>="meet me"
<LocationIndicator>="@"
<Location>="home"
"meet me in the kitchen @home":
<Text>="meet me in the kitchen"
<LocationIndicator>="@"
<Location>="home"
" meet me @ home ":
<Text>="meet me"
<LocationIndicator>="@"
<Location>="home"
"meet me":
<Text>="meet me"
<LocationIndicator>=""
<Location>=""这个正则表达式做了我们需要做的事情,但前提是我们要包含@短语:
^\s*(((?<Text>.*)?)\s*((?<LocationIndicator>(?:@)+?)\s*(?<Location>.*)))\s*$如果我们排除@短语,我们将得不到任何匹配。换句话说,这无法匹配/分组:
"meet me":
<Text>="meet me"
<LocationIndicator>=""
<Location>=""我们已经尝试包括一个?在LocationIndicator/Location组之后,但这会将短语与文本分组:
^\s*(((?<Text>.*)?)\s*((?<LocationIndicator>(?:@)+?)\s*(?<Location>.*))?)\s*$
"meet me @home":
<Text>="meet me @home"
<LocationIndicator>=""
<Location>=""我们如何用一个表达式匹配所有给出的例子?
注意:我们在C#中使用这些正则表达式
发布于 2012-05-10 04:14:50
添加?后,您的方向是正确的。此外,您需要做的是(至少)将第一个通配符.*替换为排除您的位置指示符的内容,例如[^@]*。
编辑:我简化了您的表达式(有一些额外的括号和一个不必要的非贪婪的-fier),并对其进行了测试。
^\s*(?<Text>[^@]*)?\s*(?:(?<LocationIndicator>[@]+)\s*(?<Location>.*))?\s*$参见http://rubular.com/r/C5lfx9cvtZ。
https://stackoverflow.com/questions/10523055
复制相似问题