Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex find token value in .NET

Tags:

c#

.net

regex

I need some help from someone that is better in Regex than I am :)

I am trying to find the values of specific tokens in a string using .NET (C#)

The string I have has tokens like this one {token:one}

The function I have is as follows:

public static ArrayList GetMatches(string szInput)
{
    // Example string
    // Lorem ipsum {token:me} lala this {token:other} other stuff
    ArrayList aResults = new ArrayList();
    string szPattern = @"(\{token:(*)\})";

    foreach (Match match in Regex.Matches(szInput, szPattern))
    {
        aResults.Add(match.Value);
    }
    // It should contain me and other
    return aResults;
}

Any pointers would be more than appreciated.

like image 966
Nikolaos Dimopoulos Avatar asked Feb 16 '23 07:02

Nikolaos Dimopoulos


1 Answers

You are just missing the "." to match any character before the *.

string szPattern = @"(\{token:(.*)\})";

Also, you don't need the surrounding "()" if you don't need to match the entire expression, so you could simplify to

string szPattern = @"\{token:(.*)\}";

now the matching group only contains the "one" in your example.

If you want to match multiple tokens in the same line you will need to extend it to match one or more token instances with the + operator

string szPattern = @"(\{token:(.*?)\})+";
like image 184
greedybuddha Avatar answered Feb 18 '23 20:02

greedybuddha