Reputation: 1359
I have a string like this:
<random stuff between><random stuff between><random stuff between><random stuff between>
I already can match this string using this Regex Pattern :
if (Regex.IsMatch(arg, "^(<.+>){4}$"))
return true;
But How can I get the content between the brackets, by also using Regex?
Upvotes: 0
Views: 177
Reputation: 7054
Try this code:
var source = "<abc><def><g><hij>";
var pattern = new Regex("<(?<content>[^>]+)>");
var content = pattern.Matches(source).Cast<Match>().Select(m =>
m.Groups["content"].Value).ToArray();
EDIT If you need exactly 4 groups you can use this code (from @C Perkins comment):
var pattern = new Regex("^(<(?<content>[^>]+)>){4}$");
var content2 = pattern.Match(source).Groups["content"].Captures
.Cast<Capture>().Select(c => c.Value)
.ToArray();
Upvotes: 4
Reputation: 45155
For completeness, if it's important that the match be anchored and have exactly 4 groups, then you will have to explicitly repeat the groups, which you could do like this:
^<(.+)><(.+)><(.+)><(.+)>$
although [^>]
might be a safer bet than .
Then each piece of text between the brackets will be in a separate group in your match.
Obviously this isn't very flexible when you later decide you need to have 5 matches, or 50 matches or variable number of matches. In that case, use Aleks' answer.
Finally, if it's the case that your data is actually XML or something similar, you are probably better off not using regex at all and instead using an appropriate parser.
Upvotes: 2
Reputation: 59
Use the following code and it will work.
Regex regex = new Regex(@"[\w\s]+");
string example = "<random stuff between><random stuff between>
<random stuff between><random stuff between><a><a
a>";
Match match = regex.Match(example);
while (match.Success)
{
Console.WriteLine(match);
match = match.NextMatch();
}
Upvotes: 0