MurariAlex
MurariAlex

Reputation: 331

Regex - Escape character

I have this regex: (?:\[|\G(?!^))('[^']+?')\s*,?\s*(?=[^\]]*?\]) which matches only content between quotes inside square brackets (like an array): ['Foo', 'Bar'] => returns 'Foo' 'Bar'.

The problem is that in this case the single quote is an special character, since it's used by the regex as a delimiter, but it's necessary for me to pass sometimes the single quote inside the value as a escaped character: ['F'oo', 'B'ar'].

I'm trying to do something like 'F\'oo', by adapting this non-capturing (?:(?=(\\?))\1.) group to the regex, but it doesn't work, I tried many different ways.

This non-capturing group regex comes from this answer, where the he successfully uses the backslash to escape special characters.

I use C# with .NET Core.

The full text is something like: eq('Property', ['F'oo', 'Ba'r', '123'])

How can this be solved?

Upvotes: 2

Views: 284

Answers (3)

Jan
Jan

Reputation: 43169

You could maybe use

(?:\[|\G(?!\A))
('.+?')
(?:(?:\s*,\s*)|\])

See a demo on regex101.com.

Upvotes: 2

bobble bubble
bobble bubble

Reputation: 18490

There is a similar question already for getting quoted escaped characters. I'd prefer this answer.

Change your capturing part ('[^']+?') to ('[^\\']*(?:\\.[^\\']*)*'). You can further drop the lazy quantifier which won't make much difference when using a negated class already.

It might be necessary to do additional escaping of the backslash.

Upvotes: 2

Emma
Emma

Reputation: 27723

My guess is that maybe,

(?<=\[|,)\s*'(.*?)'\s*(?=\]|,)

or some expression similar to that might work OK.

Demo

Test

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(?<=\[|,)\s*'(.*?)'\s*(?=\]|,)";
        string input = @"['Foo', 'Bar']
['F'oo', 'B'ar']
['F'oo', 'B'ar','Foo', 'Bar']";
        RegexOptions options = RegexOptions.Multiline;
        
        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Upvotes: 0

Related Questions