简体   繁体   English

通过正则表达式解析字符串

[英]parsing string by regular expression

There is a method in an old rails application. 在旧的Rails应用程序中有一种方法。 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! 请帮助,在此先感谢!

((?<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 http://regex101.com/r/sX5xT6/1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM