Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex matching excluding a specific context

Tags:

c#

regex

I'm trying to search a string for words within single quotes, but only if those single quotes are not within parentheses.

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

So for the given example I'd like to match foo, but not bar.

After searching for regex examples I'm able to match within single quotes (see below code snippet), but am not sure how to exclude matches in the context previously described.

string line = "something, 'foo', something ('bar')";
Match name = Regex.Match(line, @"'([^']*)");
if (name.Success)
{
    string matchedName = name.Groups[1].Value;
    Console.WriteLine(matchedName);
}
like image 512
stratocaster_master Avatar asked Oct 12 '16 13:10

stratocaster_master


1 Answers

I would recommend using lookahead instead (see it 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);
}
like image 99
Thomas Ayoub Avatar answered Sep 27 '22 21:09

Thomas Ayoub