2017-10-04 35 views
2

是否有可能在仍然獲得匹配的情況下在正則表達式中找到匹配的索引?例如:在字符串中查找正則表達式匹配的索引

str = "foo [bar] hello [world]" 
str.match(/\[(.*?)\]/) { |match,idx| 
    puts match 
    puts idx 
} 

不幸的是,idx在本例中爲零。

我的現實世界的問題是一個字符串,我想根據一些條件(例如,如果字符串在黑名單中)來替換某些子字符串,這些子字符串用圓括號括起來,例如,當world這個詞在黑名單中時,"foo [bar] hello [world]"應該變成"foo [bar] hello (world)"

+1

繼由Eric Duminil一個建議,我已經重構我的代碼。既然你接受我的答案(謝謝btw),一定要檢查更新:) –

回答

2

您可以使用String#gsub

blacklist = ["world"] 
str = "foo [bar] hello [world]" 

str.gsub(/\[(\w*?)\]/) { |m| 
    blacklist.include?($1) ? "(#{$1})" : m 
} 

#=> "foo [bar] hello (world)" 
+0

@eric我已經實現了你的建議重新匹配組。謝謝 –

1

如果你想每場比賽對象的枚舉,你可以使用:

def matches(string, regex) 
    position = 0 
    Enumerator.new do |yielder| 
    while match = regex.match(string, position) 
     yielder << match 
     position = match.end(0) 
    end 
    end 
end 

舉個例子:

p matches("foo [bar] hello [world]", /\[(.*?)\]/).to_a 
# [#<MatchData "[bar]" 1:"bar">, #<MatchData "[world]" 1:"world">] 
p matches("foo [bar] hello [world]", /\[(.*?)\]/).map{|m| [m[1], m.begin(0)]} 
# [["bar", 4], ["world", 16]] 

你可以得到匹配的字符串,然後從匹配對象的索引。

但實際上,它看起來像你需要gsub與塊:

"foo [bar] hello [world]".gsub(/\[(.*?)\]/){ |m| # define logic here } 
相關問題