Ruby on rails 正则表达式从字符串中提取邮政编码
我有一个用户输入文本的搜索字符串 如果它包含邮政编码的任何部分,如:1N1或1N11N1或1N11N1,那么我想从文本中提取出来 例如:Ruby on rails 正则表达式从字符串中提取邮政编码,ruby-on-rails,ruby,regex,Ruby On Rails,Ruby,Regex,我有一个用户输入文本的搜索字符串 如果它包含邮政编码的任何部分,如:1N1或1N11N1或1N11N1,那么我想从文本中提取出来 例如: John Doe 1n11n1 或 或 我想抓住这一点: postal_code: 1n11n1 other: John Doe 这可以用regex完成吗?不确定您所在的邮政编码格式,但我肯定会使用regexlib: 您会发现许多正则表达式可以用来匹配字符串中的邮政编码。 要获取字符串的其余部分,只需对邮政编码执行正则表达式删除,并获取结果字符串。也许有
John Doe 1n11n1
或
或
我想抓住这一点:
postal_code: 1n11n1
other: John Doe
这可以用regex完成吗?不确定您所在的邮政编码格式,但我肯定会使用regexlib: 您会发现许多正则表达式可以用来匹配字符串中的邮政编码。 要获取字符串的其余部分,只需对邮政编码执行正则表达式删除,并获取结果字符串。也许有一种更有效的方法可以做到这一点,但为了简单起见,我要说:)
希望这有帮助 是的,这可以使用正则表达式来完成。根据行中数据的类型,您可能会面临误报风险,因为任何与该模式匹配的内容都将被视为邮政编码(在您的示例中,这似乎不太可能) 假设在您的模式中,N是字母字符,1是数字字符,您可以执行如下操作:
strings = ["John Doe 1n11n1", "1n1 John Doe", "John 1n1 1n1 Doe"]
regex = /([0-9]{1}[A-Za-z]{1}[0-9]{2}[A-Za-z]{1}[0-9]{1}|[0-9]{1}[A-Za-z]{1}[0-9]{1}\s[0-9]{1}[A-Za-z]{1}[0-9]{1}|[0-9]{1}[A-Za-z]{1}[0-9]{1})/
strings.each do |s|
if regex.match(s)
puts "postal_code: #{regex.match(s)[1]}"
puts "rest: #{s.gsub(regex, "")}"
puts
end
end
这将产生:
postal_code: 1n11n1
rest: John Doe
postal_code: 1n1
rest: John Doe
postal_code: 1n1 1n1
rest: John Doe
如果您想消除多余的空格,可以使用String#squese(“”)来实现:)尝试匹配正则表达式
/((?:\d[A-Za-z]\d)+/
,并返回$1
:
def get_postal_code(s)
r = /((?:\d[A-Za-z]\d)+)/
return (s =~ r) ? [$1, s.sub(r,'')] : nil
end
# Example usage...
get_postal_code('John Doe 1n11n1') # => ['1n11n1', 'John Doe ']
get_postal_code('1n1 John Doe') # => ['1n1', ' John Doe']
get_postal_code('John Doe 1n1') # => ['1n1', 'John Doe ']
您还可以按如下方式清理“other”字符串
...
return (s =~ r) ? [$1, s.sub(r,'').gsub(/\s+/,' ').strip] : nil
end
get_postal_code('John Doe 1n11n1') # => ['1n11n1', 'John Doe']
get_postal_code('1n1 John Doe') # => ['1n1', 'John Doe']
get_postal_code('John Doe 1n1') # => ['1n1', 'John Doe']
我不明白1N1这个比喻。
def get_postal_code(s)
r = /((?:\d[A-Za-z]\d)+)/
return (s =~ r) ? [$1, s.sub(r,'')] : nil
end
# Example usage...
get_postal_code('John Doe 1n11n1') # => ['1n11n1', 'John Doe ']
get_postal_code('1n1 John Doe') # => ['1n1', ' John Doe']
get_postal_code('John Doe 1n1') # => ['1n1', 'John Doe ']
...
return (s =~ r) ? [$1, s.sub(r,'').gsub(/\s+/,' ').strip] : nil
end
get_postal_code('John Doe 1n11n1') # => ['1n11n1', 'John Doe']
get_postal_code('1n1 John Doe') # => ['1n1', 'John Doe']
get_postal_code('John Doe 1n1') # => ['1n1', 'John Doe']