Reputation: 3813
I have this:
string input = @"(+order: top* OR +order: first* OR +order: second* OR +order: third* OR +order: ""fourth top"" OR +order: fifth*)";
I need to get a regex that extracts from the above as follows:
"top, first, second, third, fourth top, fifth"
I made this
public static string GetOrders(string input)
{
string pattern = @"order(.*)OR";
List<string> orders = new List<string>();
foreach (Match m in Regex.Matches(input, pattern))
orders.Add(m.Value);
return string.Join(", ", orders.ToArray());
}
My regex pattern is incomplete. I thought I can just extract everythin between "+order:" and "OR", but it's not working. It doesn't seem to iterate the elements, I just get the whole input string.
What am I doing wrong?
Upvotes: 2
Views: 548
Reputation: 336148
.*
is greedy, matching from the first order
to the last OR
.
@"order(.*?)OR"
would work but only for the first four matches; the fifth one isn't followed by OR
.
So a better regex would be
@"order:\s*(.*?)\s*(?:OR|\))"
Even better (assuming that the rule is "either the parameter contains no spaces and ends with *
, or it contains spaces and is enclosed in "
s"):
@"(?<=order:\s*)(?:""[^""]*""|[^""*\s]*)"
Upvotes: 3