It is necessary to combine the first part of the sentence, down to a certain word. However, this word is optional, in which case I want to match the whole sentence. For example:
I have a proposal with a proposal that I do not want.
I have a suggestion and I like it.
In the first case, I want "I have a sentence" . In the second case, I want "I have a sentence and I like it."
Lookarounds will give me the first case, but as soon as I try to make it optional to cover the second case, I get the first sentence. I tried to make the expression lazy ... without a bone.
Code that works for the first case:
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 : ("); }
The expression I would like to work:
var regEx = new Regex(@".*(?=with)?");
Any suggestions?
Thanks in advance!
James
c # regex
James king
source share