Andrei
Andrei

Reputation: 44580

Regex matches incorrect value

I am using C#. I need regex to examine text like that:

abc {val2:123} lorem ipsum {val1:234}

I need to match all the {x:y}. I've tried regex {.*} but it matches the whole value - "{val2:123} lorem ipsum {val1:234}". Of course It's not fun.

How to change my regex approppriately?

Upvotes: 1

Views: 404

Answers (4)

Ibrahim Najjar
Ibrahim Najjar

Reputation: 19423

\{([^}]*)\}

This matches a { followed by zero or more characters that are not a } then it matches a literal }, it puts whatever that was matched into group 1.

You can then split the captured group on the colon symbol : to get the key and value pair.

Regex101 Demo

Upvotes: 2

nightsnaker
nightsnaker

Reputation: 471

That happens because c sharp regex is greedy by default. Just use {.*?}

The following code will do exactly what you want. That's all about that question mark that makes the regex nongreegy.

string s = "abc {val2:123} lorem ipsum {val1:234};";
MatchCollection nonGreedyMatches = Regex.Matches(s, @"{.*?}");

Upvotes: 2

MBender
MBender

Reputation: 5650

{(?<param>\w+):(?<value>\w+)}

The above should work... I've already included named groups to make selecting values easier.

Upvotes: 2

I4V
I4V

Reputation: 35353

string input = "abc {val2:123} lorem ipsum {val1:234}";
var dict = Regex.Matches(input, @"\{(.+?):(.+?)\}").Cast<Match>()
            .ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value);

Upvotes: 4

Related Questions