SamFisher83
SamFisher83

Reputation: 3995

How do I regex for multiple items within a single string with c#?

My string is the following format:

"[Item1],[Item2],[Item3],..."

I want to be able to get item1, item2, item3, etc.

I am trying the following grep expression:

MatchCollection matches = Regex.Matches(query, @"\[(.*)\]?");

However, instead of match each item, it is getting "item1][item2][..."

What I am doing wrong?

Upvotes: 1

Views: 110

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149020

You need to use a non-greedy quantifier, like this:

MatchCollection matches = Regex.Matches(query, @"\[(.*?)\]?");

Or a character class that excludes ] characters, like this:

MatchCollection matches = Regex.Matches(query, @"\[([^\]]*)\]?");

You can then access your matches just like this:

matches[0].Groups[1].Value // Item1
matches[1].Groups[1].Value // Item2
matches[2].Groups[1].Value // Item3

Upvotes: 5

Related Questions