Reputation: 15
I have this text and I want to get the 2 matches from it but the problem is I am always getting only 1 match. This is the sample code in c#
string formattedTag = "{Tag 1}::[FORMAT] asdfa {Tag 2}::[FORMAT]";
var tagMatches = Regex.Matches(formattedTag, @"(\{.+\}\:\:\[.+\])");
i am expecting to get two matches here "{Tag 1}::[FORMAT]" and "{Tag 2}::[FORMAT]" but the result of this code is the actual value of the variable formattedTag. It must be something from regexp pattern so can somebody help me to figure it out?
I will appreciate every help. Thanks in advance!
Upvotes: 0
Views: 68
Reputation: 1
string formattedTag = "{tag 1}::[admin] adfaf{tag 2}::[test.user]";
var tagMatches = Regex.Matches(formattedTag, @"\{(\w+\s*\d{1,2})\}::\[(.*?)\]");
foreach(Match item in tagMatches)[enter image description here][1]{
Console.WriteLine(item.Groups[0]);
Console.WriteLine(item.Groups[1] + "=" + item.Groups[2]);
}
Upvotes: 0
Reputation: 1985
You need to use the following regular expression:
(\{[^}]+\}\:\:\[[^]]+\])
You want to match any character except the closing bracket within your bracketed portions of the string, otherwise the whole string is matched because regular expressions are greedy and attempt to retrieve the longest match.
Upvotes: 1