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?
To run a “whole words only” search using a regular expression, simply place the word between two word boundaries, as we did with ‹ \bcat\b ›. The first ‹ \b › requires the ‹ c › to occur at the very start of the string, or after a nonword character.
$ means "Match the end of the string" (the position after the last character in the string).
Use square brackets [] to match any characters in a set. Use \w to match any single alphanumeric character: 0-9 , a-z , A-Z , and _ (underscore). Use \d to match any single digit. Use \s to match any single whitespace character.
There are several ways to do this. You could do something like this:
^(.*?)(with|$)
The first group is matched reluctantly, i.e. as few characters as possible. We have an overall match if this group is followed by either with
or the end of the line $
anchor.
Given this input:
I have a sentence with a clause I don't want.
I have a sentence and I like it.
Then there are two matches (as seen on rubular.com):
"I have a sentence "
"with"
"I have a sentence and I like it"
.""
(empty string)You can make the grouped alternation non-capturing with (?:with|$)
if you don't need to distinguish the two cases.
.*?
and .*
for regexIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With