正则表达式从字符串
问题描述:
拉出邮政编码我有一个搜索字符串,用户输入的文本。正则表达式从字符串
如果它包含的邮政编码就像任何部分:1N1或1N11N1或1N1 1N1然后我想拉说出来的文字。
例如:
John Doe 1n11n1
或
1n1 John Doe
或
John 1n11n1 Doe
我想抓住这个:
postal_code: 1n11n1
other: John Doe
这可以使用正则表达式来完成吗?
答
不知道什么是你所在的邮政编码的格式,但我肯定会诉诸regexlib: http://regexlib.com/Search.aspx?k=postal%20code
你会发现,你可以用它来在匹配邮政编码许多正则表达式你的字符串。 要获得字符串的休息,你可以简单地做一个正则表达式卸下邮政编码和获得结果字符串。有可能是一个更有效的方式来做到这一点,但我要为简单起见:)
希望这有助于!
答
是的,这可以通过使用正则表达式来完成。根据行中数据的类型,您可能会有误报的风险,因为符合模式的任何内容都将被视为邮政编码(在您的示例中,尽管看起来不太可能)。
假设在你的模式,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#squeeze(“”)来使它变得如此:)
答
尝试匹配正则表达式/((?:\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 ']
您还可以按如下方式清理“其他”字符串。
...
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'隐喻。 – Kobi 2011-05-26 18:55:42
号码字母数字 – Blankman 2011-05-26 19:19:18