正则表达式在.NET中找到令牌值

Nik*_*los 3 .net c# regex

我需要一些在Regex上比我更好的人的帮助:)

我试图使用.NET(C#)在字符串中查找特定标记的值

我拥有的字符串有这样的标记 {token:one}

我的功能如下:

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;
}
Run Code Online (Sandbox Code Playgroud)

任何指针都不仅仅是值得赞赏的.

gre*_*dha 5

你只是错过了"." 匹配之前的任何字符*.

string szPattern = @"(\{token:(.*)\})";
Run Code Online (Sandbox Code Playgroud)

此外,如果您不需要匹配整个表达式,则不需要周围的"()",因此您可以简化为

string szPattern = @"\{token:(.*)\}";
Run Code Online (Sandbox Code Playgroud)

现在,匹配组仅包含示例中的"one".

如果要在同一行中匹配多个令牌,则需要对其进行扩展以使一个或多个令牌实例与+运算符匹配

string szPattern = @"(\{token:(.*?)\})+";
Run Code Online (Sandbox Code Playgroud)