2Fast4YouBR
2Fast4YouBR

Reputation: 1042

Regex .net multiple line

I have these examples:

{I18n.get("Testing 123...")}

{I18n.get('Testing 123...')}

    {I18n.get(
            "Testing 123..."
     )}
    
    {I18n.get("Testing 123..."
     )}
    
    {I18n.get(
            "Testing 123...")}
        
        

I want to extract the 'Testing 123...' in .Net using C# Regex. What I did was:

        Regex r = new Regex(@"(?:I18n.get\(""(.+?)""\))", RegexOptions.IgnoreCase | RegexOptions.Singleline);

        var matches = r.Matches(txt)
                        .Select(xx=> xx.Groups)
                        .Select(xx=> xx.Last().Value)
                        .ToList(); 

When is single line works perfect, but when is multiple line it fails...

And how would be possible to match in a single Regex when the txt is with double quotes " or when is with single quotes ' ?

Upvotes: 2

Views: 70

Answers (2)

user13843220
user13843220

Reputation:

I contend it doesn't matter which open/close quotes should be in the regex when you don't intend to actually parse it as a quoted string, right ?
I mean with all the embed escapes etc...

Use what you know as the delimiters, the text literals
I18n.get( stuff here )

You could use a sub validation that there's an inner quote, but since you're
not parsing quotes, it's not going to be strictly valid anyway.
Here, we just use it to trim so it's not matched and be part of element.

Here it is, the whole match is the value you're looking for, toss it into an array.

@"(?s)(?<=I18n\s*\.\s*get\s*\(\s*['""]\s*).*?(?=\s*['""]\s*\))"

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626690

You may use

var r = new Regex(@"I18n\.get\(\s*(""|')(.*?)\1\s*\)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
var results = r.Matches(txt).Cast<Match>().Select(x => x.Groups[2].Value).ToList();

See the regex demo.

Details

  • I18n\.get\( - a literal I18n.get( text
  • \s* - 0+ whitespaces
  • ("|') - Group 1: " or '
  • (.*?) - Group 2: any char, 0 or more occurrences, as few as possible
  • \1 - same value as captured in Group 1
  • \s* - 0+ whitespaces
  • \) - a ) char.

Upvotes: 1

Related Questions