2011-05-26 321 views
0

拉出郵政編碼我有一個搜索字符串,用戶輸入的文本。正則表達式從字符串

如果它包含的郵政編碼就像任何部分:1N1或1N11N1或1N1 1N1然後我想拉說出來的文字。

例如:

John Doe 1n11n1 

1n1 John Doe 

John 1n11n1 Doe 

我想抓住這個:

postal_code: 1n11n1 
other: John Doe 

這可以使用正則表達式來完成嗎?

+1

我沒有得到'1N1'隱喻。 – Kobi 2011-05-26 18:55:42

+0

號碼字母數字 – Blankman 2011-05-26 19:19:18

回答

3

不知道什麼是你所在的郵政編碼的格式,但我肯定會訴諸regexlib: http://regexlib.com/Search.aspx?k=postal%20code

你會發現,你可以用它來在匹配郵政編碼許多正則表達式你的字符串。 要獲得字符串的休息,你可以簡單地做一個正則表達式卸下郵政編碼和獲得結果字符串。有可能是一個更有效的方式來做到這一點,但我要爲簡單起見:)

希望這有助於!

1

是的,這可以通過使用正則表達式來完成。根據行中數據的類型,您可能會有誤報的風險,因爲符合模式的任何內容都將被視爲郵政編碼(在您的示例中,儘管看起來不太可能)。

假設在你的模式,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(「」)來使它變得如此:)

4

嘗試匹配正則表達式/((?:\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']