jeudi 20 juin 2019

Regex.Matches find least amount of characters per each match found

I want to iterate over each match but my code only finds 1 match by getting everything between the first and last character to find in the pattern.

Basically, I want to iterate over the 3 matches found in the following string:

value = "{account_id}{user_id}{someValue}";

But it only finds 1 match (the whole thing) using the following pattern: "{\\S+}"

foreach (Match match in Regex.Matches(value, "{\\S+}"))
{
    var key = match.Value.Replace("{", "").Replace("}", "").Trim();
    // do stuff with key...
}

This makes sense because "{" and "}" are both non-white space character so I tried using "{[a-zA-Z_]}" but this fails too.

foreach (Match match in Regex.Matches(value, "{[a-zA-Z_]}"))
{
    var key = match.Value.Replace("{", "").Replace("}", "").Trim();
    // do stuff with key...
}

Variable key in the loop should be "account_id", then "user_id", then "someValue", however it is always "account_iduser_idsomeValue (the whole thing).

How can I fix this?

Aucun commentaire:

Enregistrer un commentaire