2

There is a method in an old rails application. it can convert a string into an array by regular expression.

Just like this:

irb(main):047:0> string = "[(a+50%+1)(b+60%+2)]"
=> "[(a+50%+1)(b+60%+2)]"
irb(main):048:0> string.scan(/\((?<name>\w+)\+(?<percent>\d+)%\+(?<num>\d+)\)/)
=> [["a", "50", "1"], ["b", "60", "2"]]

But requirement is changed, I have to add a new value to the string.

I can make it like this:

irb(main):049:0> string = "[(a+50%+1+100)(b+60%+2+200)]"
=> "[(a+50%+1+100)(b+60%+2+200)]"
irb(main):050:0> string.scan(/\((?<name>\w+)\+(?<percent>\d+)%\+(?<num>\d+)\+(?<max>\d+)\)/)
=> [["a", "50", "1", "100"], ["b", "60", "2", "200"]]

but it can't compatible with the previous,

irb(main):051:0> string = "[(a+50%+1)(b+60%+2)]"
=> "[(a+50%+1)(b+60%+2)]"
irb(main):052:0> string.scan(/\((?<name>\w+)\+(?<percent>\d+)%\+(?<num>\d+)\+(?<max>\d+)\)/)
=> []

Is there better way to make it? please help, thanks in advance!

3
  • Wow, I didn't know it could work that way. Anyway, why are you not using json or yaml ? sory off topics. Just curious Commented Nov 3, 2014 at 8:55
  • This is a old system, I also think json or yaml is better, if I do, I have to rewrite a lot of code, but not enough time. Commented Nov 3, 2014 at 9:01
  • Oh okay i thought there is a performance issue or anything. Those legacy code.. Commented Nov 3, 2014 at 9:18

1 Answer 1

3
((?<name>\w+)\+(?<percent>\d+)%\+(?<num>\d+)(?:\+(?<max>\d+))?

make the last groups optional by adding ? should make it compatible with previous version.

(?:\+(?<max>\d+))? is optional so old string match as well.

See demo.

http://regex101.com/r/sX5xT6/1

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

2 Comments

very nice!!! thanks. I think I have to take the time to learn regular expressions.
@liuzxc your regex is good.Just made the last string optional.

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.