smintz
smintz

Reputation: 135

ruby regular expression replace repeated matches on string

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

Upvotes: 1

Views: 745

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

The greedy .* matches too much. It means "any string, maximum possible length". So the first (.*) matches 1,Micheal}, my name is {2, then the comma matches the comma, and the second (.*) matches Shahar (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:

text.gsub(/\{([^{}]*),([^{}]*)\}/, "\\2(\\1)")

Or you could do this:

text.gsub(/\{([^,]*),([^}]*)\}/, "\\2(\\1)")

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 }.

Upvotes: 1

Related Questions