2013-03-22 182 views
0

我有一個字符串,如下所示:搜索一個字母的所有出現偏移字符串

--d--d-d---d-- 

我想找個「d」中出現的所有該字符串的偏移量。

但是,這樣做下面只給我回的第一個結果:

irb(main):001:0> m = /d/.match "d--d-d---d" 
=> #<MatchData "d"> 
irb(main):002:0> m.size 
=> 1 

我在做什麼錯?我認爲match將匹配字符串中所有的正則表達式。

回答

0

要得到補償,你可以使用這樣一個循環:

s = '--d--d-d---d--' 
offset = 0 
while md = /d/.match(s,offset) 
    p md.offset(0)[1]   
    # MatchDate#offset Returns a two-element array 
    # containing the beginning and ending offsets 
    offset = md.offset(0)[1] 
end 
+0

謝謝,但我仍然不明白爲什麼它不包含所有匹配,根據核心文檔(http://www.ruby-doc.org/core-2.0/MatchData.html )聽起來應該是這樣,除非我失去了一些東西。 – mydoghasworms 2013-03-22 11:42:02

+1

@mydoghasworms'#match'只運行一次正則表達式。 MatchData包含整個比賽和每個捕獲組的偏移量。 – dbenhur 2013-03-22 15:35:46

+0

當'index'直接返回所需的偏移量時,爲什麼要循環匹配和匹配數據? – dbenhur 2013-03-22 15:59:52

0

作爲一種變體:

str = '--d--d-d---d--' 
str.each_char.with_index.select{|el| el[0] == "d"}.map(&:last) 

結果:

[2, 5, 7, 11] 

公正立場,從0開始。如果你需要它用1 with_index(1)開始,所以結果將是:

[3, 6, 8, 12] 
+0

當模式是單個字符時,這很好地工作,但如果它是一個正則表達式,則不會。 – dbenhur 2013-03-22 15:56:54

0

Regexp#match只運行一次模式。 MatchData可以包含多個匹配,因此可以包含multiple offsets。第一個是整個匹配,其他是正則表達式中捕獲組的內容。 MatchData中沒有任何由正則表達式的多個應用程序產生的結果。

String#index直接產生偏移量,可以很容易地用來遍歷字符串。

s = '--d--d-d---d--' 
[].tap{ |offsets| i=-1; while i = s.index('d', i+1); offsets << i; end } 
=> [2, 5, 7, 11] 
相關問題