使用ruby regex提取在字符串中多次出现的模式

时间:2022-09-13 11:45:30

I want to extract patterns that appert multiple times in a string. For example,getting two an array lay of two digit integers from a string

我想在字符串中多次提取appert的模式。例如,从字符串中获取两个数组的两位数整数

wahoaet56oihaioet67jlkiwoeah67ladohwae45lkaowearho56

wahoaet56oihaioet67jlkiwoeah67ladohwae45lkaowearho56

I thought result="wahoaet56oihaioet67jlkiwoeah67ladohwae45lkaowearho56".match(/([0-9]{2})/) should give a MatchData object whose captures method should give me an array of matched patters, but it seems there is something I am missing. It only give back the first find. Even using $1,$2,$3 etc doesn't work. I am using ruby

我认为result =“wahoaet56oihaioet67jlkiwoeah67ladohwae45lkaowearho56”.match(/([0-9] {2})/)应该给出一个MatchData对象,其捕获方法应该给我一个匹配模式的数组,但似乎有一些我缺少的东西。它只回馈第一个发现。即使使用1美元,2美元,3美元等也行不通。我正在使用红宝石

How should I do this?

我该怎么做?

2 个解决方案

#1


10  

string.scan(/regex/)

should do it

应该这样做

#2


5  

scan does what you want:

扫描做你想要的:

str = "wahoaet56oihaioet67jlkiwoeah67ladohwae45lkaowearho56"
p str.scan(/\d+/) #=> ["56", "67", "67", "45", "56"]

#1


10  

string.scan(/regex/)

should do it

应该这样做

#2


5  

scan does what you want:

扫描做你想要的:

str = "wahoaet56oihaioet67jlkiwoeah67ladohwae45lkaowearho56"
p str.scan(/\d+/) #=> ["56", "67", "67", "45", "56"]