I need to parse a string in ruby which contain vars of ids and names like this {2,Shahar}.
The string is like this:
text = "Hello {1,Micheal}, my name is {2,Shahar}, nice to meet you!"
when I am trying to parse it, the regexp skips the first } and I get something like this:
text.gsub(/\{(.*),(.*)\}/, "\\2(\\1)")
=> "Hello Shahar(1,Micheal}, my name is {2), nice to meet you!"
while the required resault should be:
=> "Hello Michael(1), my name is Shahar(2), nice to meet you!"
I would be thankful to anyone who can help.
Thanks
Shahar
The greedy
.*matches too much. It means “any string, maximum possible length”. So the first(.*)matches1,Micheal}, my name is {2, then the comma matches the comma, and the second(.*)matchesShahar(and the final\}matches the closing braces.Better be more specific. For example, you could restrict the match to allow only characters except braces to ensure that a match will never extend beyond the scope of a
{...}section:Or you could do this:
where the first part may be any string that doesn’t contain a comma, the second part may be any string that doesn’t contain a
}.