正则表达式从字符串拔出邮政编码

问题描述

我有一个用户输入文本的搜索字符串。 如果它包含邮政编码的任何部分,例如:1N1或1N11N1或1N1 1N1,那么我想将其从文本中拉出。 例:
John Doe 1n11n1
要么
1n1 John Doe
要么
John 1n11n1 Doe
我想捕捉一下:
postal_code: 1n11n1
other: John Doe
可以使用正则表达式来完成吗?     

解决方法

尝试匹配正则表达式
/((?:\\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,\'\').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\']
    ,不知道您所在的邮政编码是什么格式,但是我绝对会使用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(\“ \”)来做到这一点:)     

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...