简体   繁体   English

正则表达式红宝石

[英]Regular Expressions ruby

"(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)"

Only the first line does not need any change. 只有第一行不需要任何更改。 In the bottom three lines I need to put the address in parenthesis because it has two or more words after the colon. 在底部的三行中,我需要将地址放在括号中,因为它在冒号后面有两个或更多的单词。

For example for the second row the modified output should be 例如,对于第二行,修改后的输出应为

"(fname:John OR address:(1200 main str va)) (male OR female)"

I tried to do it with regex but I am struggling with how to tell regex to look for until you encounter the world OR but if you come across "(" or ")" then stop. 我试图用正则表达式来做这件事,但我正在努力告诉正则表达式如何寻找直到你遇到世界或者如果你遇到“(”或“)”然后停止。


e.gsub /address:(.*?(?=( *OR| *\))))/, 'address:(\1)'

Or, with a test case wrapper... 或者,使用测试用例包装器......

[ "(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

Returning... 返回...

(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)

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

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