Catch all words between 2 characters

Asked

Viewed 55 times

0

Text: var texto = "if(true) { {{palavra1}} + {{palavra2}}; }"

The only characters I know will ever exist are {{ and }}.

I did so, but this way I only get the first word:

Regex r = new Regex(@"\{\{[^\}]+?\}\}");
Match m = r.Match(texto);
Console.Write(m); 
// Resultado: {{palavra1}}

What I desire:

{{palavra1}}
{{palavra2}}
  • as I said, I managed to catch, the problem is to get all that you have in the string

  • I took the {{palavra1}} only, need the {{palavra2}} also and how many more there are in the string

  • 1

    @danieltakeshi does not fit the problem. The problem is not in the expression, it is in how it is being manipulated in the object.

1 answer

1


The method Regex.Match will only return the first occurrence of what you found in the entry. To get all the results, use the method Regex.Matches, in which returns all occurrences.

public class Program
{
    public static void Main()
    {
        var texto = "if(true) { {{palavra1}} + {{palavra2}}; }";
        Regex r = new Regex(@"\{\{[^\}]+?\}\}");
        var m = r.Matches(texto);
        foreach(var match in m)
            Console.WriteLine(match);   
    }
}

See working on .NET Fiddle.

Documentation of Match and of Matches.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.