Need to match the first part of a sentence, up to a given word. However, that word is optional, in which case I want to match the whole sentence. For example:
I have a sentence with a clause I don't want.
I have a sentence 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 whole first sentence. I've tried making the expression lazy... no dice.
The 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 that I wish worked:
var regEx = new Regex(@".*(?=with)?");
Any suggestions?
Thanks in advance!
James