2010-11-25 14 views
10
string = "Jack and Jill went up the hill to fetch a pail of water. Jack fell down and broke his crown. And Jill came tumbling after. " 
d = string.match(/(jack|jill)/i) # -> MatchData "Jill" 1:"Jill" 
d.size # -> 1 

Ceci correspond seulement à la première occurrence qu'il semble.
string.scan fait le travail partiellement mais il ne dit rien sur l'index du motif apparié. Comment puis-je obtenir une liste de toutes les instances appariées du modèle et de leurs indices (positions)?Comment obtenir les index de toutes les occurrences d'un modèle dans une chaîne

Répondre

19

Vous pouvez utiliser la variable globale .scan et $`, ce qui signifie La chaîne à gauche du dernier match réussi, mais il ne fonctionne pas à l'intérieur d'habitude .scan, donc vous avez besoin de ce pirater (volé this answer) :

string = "Jack and Jill went up the hill to fetch a pail of water. Jack fell down and broke his crown. And Jill came tumbling after. " 
string.to_enum(:scan, /(jack|jill)/i).map do |m,| 
    p [$`.size, m] 
end 

sortie:

[0, "Jack"] 
[9, "Jill"] 
[57, "Jack"] 
[97, "Jill"] 

UPD:

Notez le comportement de lookbehind - vous obtenez l'indice de la partie vraiment adapté, pas le regard un:

irb> "ab".to_enum(:scan, /ab/ ).map{ |m,| [$`.size, $~.begin(0), m] } 
=> [[0, 0, "ab"]] 
irb> "ab".to_enum(:scan, /(?<=a)b/).map{ |m,| [$`.size, $~.begin(0), m] } 
=> [[1, 1, "b"]] 
+1

nice one .REMERCIE beaucoup –

+0

est ici une modification si vous voulez mettre juste les emplacements de Jack dans un tableau loc_array = Array.new string = "Jack et Jill montèrent la colline pour aller chercher un seau d'eau. Jack est tombé et a cassé sa couronne. Et Jill est tombé après. " string.to_enum (: scan,/(prise)/i) .map do | m, | loc_array.push [$' .size] fin – emery

1

Voici une modification de la réponse de Nakilon si vous voulez mettre juste les emplacements des « Jack » dans un tableau

location_array = Array.new 

string = "Jack and Jack went up the hill to fetch a pail of Jack..." 
string.to_enum(:scan,/(jack)/i).map do |m,| 
    location_array.push [$`.size] 
end