Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match a string NOT surrounded by brackets

Tags:

c#

regex

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:

  • [with]
  • [ with ]
  • [sometext with sometext]
  • [sometext with]
  • [with sometext]

Here are some examples where with IS keyword

  • with
  • ] with
  • hello with
  • hello with world
  • hello [ world] with hello
  • hello [ world] with hello [world]

Anyone to help? Thanks in advance.

like image 577
Mohayemin Avatar asked Aug 10 '11 04:08

Mohayemin


1 Answers

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 [^[\]]*.

like image 120
Tim Pietzcker Avatar answered Nov 10 '22 14:11

Tim Pietzcker