需要匹配句子的第一部分,直到给定的单词。但是,该词是可选的,在这种情况下我想匹配整个句子。例如:
I have a sentence with a clause I don't want.
I have a sentence and I like it.
在第一种情况下,我想要“我有一个句子”
。在第二种情况下,我想要“我有一句话,我喜欢它。”
Lookarounds 会给出第一种情况,但一旦我尝试将其设为可选以涵盖第二种情况,我就会得到整个第一句话。我试过让表达变得懒惰……不行。
适用于第一种情况的代码:
var regEx = new Regex(@".*(?=with)");
string matchstr = @"I have a sentence with a clause I don't want";
if (regEx.IsMatch(matchstr)) {
Console.WriteLine(regEx.Match(matchstr).Captures[0].Value);
Console.WriteLine("Matched!");
}
else {
Console.WriteLine("Not Matched : (");
}
我希望有效的表达式:
var regEx = new Regex(@".*(?=with)?");
有什么建议吗?
最佳答案
有几种方法可以做到这一点。你可以这样做:
^(.*?)(with|$)
第一组勉强匹配,即尽可能少的字符。如果此组后跟 with
或行尾 $
anchor,则我们有一个整体匹配.
鉴于此输入:
I have a sentence with a clause I don't want.
I have a sentence and I like it.
然后有两个匹配项(as seen on rubular.com):
- 匹配 1:
- 第 1 组:
“我有一句话”
- 第 2 组:
“与”
- 第 1 组:
- 第 2 场比赛:
- 第 1 组:
“我有一个句子,我喜欢它”
。 - 第 2 组:
""
(空字符串)
- 第 1 组:
如果您不需要区分这两种情况,您可以使用 (?:with|$)
将分组交替设置为非捕获。
相关问题
关于c# - 正则表达式 : Match up to an optional word,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3586286/