Regular expression matching, excluding specific context

I am trying to find a string for words in single quotes, but only if these single quotes are not in parentheses.

Example line: something, 'foo', something ('bar')

So, for this example, I would like to combine foo, but not bar.

After searching for examples of regular expressions, I can match in single quotes (see the code snippet below), but I'm not sure how to exclude matches in the context described earlier.

string line = "something, 'foo', something ('bar')";
Match name = Regex.Match(line, @"'([^']*)");
if (name.Success)
{
    string matchedName = name.Groups[1].Value;
    Console.WriteLine(matchedName);
}
+4
source share
2 answers

I would recommend using lookahead instead (see live ) using:

(?<!\()'([^']*)'(?!\))

Or with C #:

string line = "something, 'foo', something ('bar')";
Match name = Regex.Match(line, @"(?<!\()'([^']*)'(?!\))");
if (name.Success)
{
    Console.WriteLine(name.Groups[1].Value);
}
+3
source

, , , , , :

\([^()]*\)|'([^']*)'

regex

  • \( - a (
  • [^()]* - 0+, ( )
  • \) - a )
  • | -
  • ' - a '
  • ([^']*) - 1, 0+, '
  • ' - .

# .Groups[1].Value, . . -:

var str = "something, 'foo', something ('bar')";
var result = Regex.Matches(str, @"\([^()]*\)|'([^']*)'")
    .Cast<Match>()
    .Select(m => m.Groups[1].Value)
    .ToList();

, , .NET, lookbehind:

(?<!\([^()]*)'([^']*)'(?![^()]*\))

- regex.

  • (?<!\([^()]*) - lookbehind, , (, 0+, ( )
  • '([^']*)' - , 0+, , 1,
  • (?![^()]*\)) - , , 0 + , ( ), ) ' .

', , .

+2

Source: https://habr.com/ru/post/1657501/


All Articles