I have to parse a text where with is a key word if it is not surrounded by square brackets. I have to match the keyword with. Also, there must be word boundaries on both side of with.
Here are some examples where with is NOT a keyword:
Here are some examples where with IS keyword
Anyone to help? Thanks in advance.
You can look for the word with
and see that the closest bracket to its left side is not an opening bracket, and that the closest bracket to its right side is not a closing bracket:
Regex regexObj = new Regex(
@"(?<! # Assert that we can't match this before the current position:
\[ # An opening bracket
[^[\]]* # followed by any other characters except brackets.
) # End of lookbehind.
\bwith\b # Match ""with"".
(?! # Assert that we can't match this after the current position:
[^[\]]* # Any text except brackets
\] # followed by a closing bracket.
) # End of lookahead.",
RegexOptions.IgnorePatternWhitespace);
Match matchResults = regexObj.Match(subjectString);
while (matchResults.Success) {
// matched text: matchResults.Value
// match start: matchResults.Index
// match length: matchResults.Length
matchResults = matchResults.NextMatch();
}
The lookaround expressions don't stop at line breaks; if you want each line to be evaluated separately, use [^[\]\r\n]*
instead of [^[\]]*
.
If 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