提取数字的Ruby正则表达式
我想提取某个字符串的开始数和结束数 下面是测试用例提取数字的Ruby正则表达式,ruby,regex,Ruby,Regex,我想提取某个字符串的开始数和结束数 下面是测试用例 10000 => 1-0 100000 => 10-0 310000 => 31-0 310001 => 31-1 1200000 => 120-0 1200009 => 120-9 12000011 => 120-11 正如你所看到的,在最后一个数字之前总是有三个零。 但我不知道如何提取这两个数字 我试过以下方法 re = /[\d]+[0]{3}[\d]+/ str = '10000' # P
10000 => 1-0
100000 => 10-0
310000 => 31-0
310001 => 31-1
1200000 => 120-0
1200009 => 120-9
12000011 => 120-11
正如你所看到的,在最后一个数字之前总是有三个零。
但我不知道如何提取这两个数字
我试过以下方法
re = /[\d]+[0]{3}[\d]+/
str = '10000'
# Print the match result
str.scan(re) do |match|
puts match.to_s
end
但是上面的代码只能打印匹配字符串。请遵循下面的代码。希望这有帮助
regex_pattern = /(\d+)(0{3})(\d+)/
# For all numbers
numbers = ['10000', '100000', '310000', '310001', '1200000', '1200009', '12000011']
result = numbers.map do |number|
#Every group captured can be use here with $number like for group 1 use $1. For group 2 use $2.
number.gsub(regex_pattern) { |match_object| "#{$1}-#{$3}" }
end
p result
#For individual number
number = '10000'
p number.gsub(regex_pattern) { |match_object| "#{$1}-#{$3}" }
如果这对您有帮助或者您有任何其他疑问,请告诉我。
test=提取我的怀疑。操作?您几乎答对了,请尝试/(\d+)0{3}(\d+)/
,然后将do | match |
更改为do |开始|编号,结束|
。使用#scan时,匹配项已经是字符串,因此您可以省去#to#s调用。谢谢,我编辑了我的帖子。您可以改为编写gsub(regex,“\1-\2”)
。这将是1-000
,“\1-\3”
是正确的参数。@CodaChang-很高兴帮助您。
test =<<_
10000
100000
310000
310001
1200000
1200009
12000011
_
r = /000(?=[1-9]|0\z)/
test.lines.each { |s| puts s.chomp.gsub(r,'-') }
1-0
10-0
31-0
31-1
120-0
120-9
120-11