1

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.