2011-03-04 167 views
0
"(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)" 

只有第一行不需要任何改變。在底部三行中,我需要將地址放在括號中,因爲它在冒號後面有兩個或更多個單詞。正則表達式ruby

例如第二行修改後的輸出應該

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

我試圖用正則表達式來做到這一點,但我有多麼地告訴正則表達式來尋找,直到你遇到世界OR但如果你掙扎遇到「(」或「)」然後停止。

回答

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) 
+0

這真棒。我會盡力瞭解它是如何工作的。 – 2011-03-04 20:10:43

+0

這可能有所幫助:http://web.njit.edu/all_topics/Prog_Lang_Docs/html/ruby/syntax.html#regexp – DigitalRoss 2011-03-04 20:16:33