我需要一行 gsub 来替换字符串中的所有非数字,但前提是非数字不超过三个并且数字的总长度为 10
我有这个符合第一个条件
p "0177/385490".gsub(/((\d+)\D?(\d+)\D?(\d+)\D?+(\d+))/,'\2\3\4\5')
#=>"0177385490"
但是当我尝试这个时,{10} 检查不起作用
p "0177/385490".gsub(/((\d+)\D?(\d+)\D?(\d+)\D?+(\d+)){10}/,'\2\3\4\5')
#=>"0177/385490"
请问该怎么做?
编辑
我设法做到了这样,但是如何在单行 gsub 中做到这一点?
strings = [
"0473/385 490",
"0473/385490",
"0473 38 54 90",
"0473/385 4901" #this one is't captured
]
strings.each do |s|
if /((\d+)\D?(\d+)\D?(\d+)\D?+(\d+))/ =~ s
if "#{$2}#{$3}#{$4}#{$5}".length == 10
puts "#{$2}#{$3}#{$4}#{$5}"
end
end
end
编辑:为了说明为什么它真的需要在我的例程中成为在线 gsub,将会添加更多替换
def cleanup text
replacements = [
{:pattern => /(04\d{2}) (\d{2}) (\d{2}) (\d{2})/, :replace_with => '\1\2\3\4'},
{:pattern => /(0\d)(\/| |-)(\d{3}) (\d{2}) (\d{2})/, :replace_with => '\1\3\4\5'},
{:pattern => /(\d{6} )(\d{3})-(\d{2})/, :replace_with => '\1\2 \3'},
{:pattern => /(\d{2,4})\D?(\d{2,3})\D?(\d{2,3})/, :replace_with => '\1\2\3'}
].each{|replacement|text.gsub!(replacement[:pattern], replacement[:replace_with])}
text
end