"(fname:John OR lname:Doe) (male OR female)"
"(fname:John OR address:1200 main str va) (male OR female)"
"(address:1200 main str va OR fname:John ) (male OR female)"
"(fname:John OR address:1200 main str va OR lname:Doe) (male OR female)"
只有第一行不需要任何更改。在底部的三行中,我需要将地址放在括号中,因为它在冒号后面有两个或更多的单词。
例如,对于第二行,修改后的输出应为
"(fname:John OR address:(1200 main str va)) (male OR female)"
我尝试用正则表达式来做这件事,但我正在努力解决如何告诉正则表达式寻找,直到你遇到这个世界或者如果你遇到“(或”)“然后停止。
答案 0 :(得分:2)
e.gsub /address:(.*?(?=( *OR| *\))))/, 'address:(\1)'
或者,使用测试用例包装器......
[ "(fname:John OR lname:Doe) (male OR female)",
"(fname:John OR address:1200 main str va) (male OR female)",
"(address:1200 main str va OR fname:John ) (male OR female)",
"(fname:John OR address:1200 main str va OR lname:Doe) (male OR female)"
].each do |e|
puts e.gsub /address:(.*?(?=( *OR| *\))))/, 'address:(\1)'
end
...返回
(fname:John OR lname:Doe) (male OR female)
(fname:John OR address:(1200 main str va)) (male OR female)
(address:(1200 main str va) OR fname:John ) (male OR female)
(fname:John OR address:(1200 main str va) OR lname:Doe) (male OR female)