2011-03-10 71 views
5

我們有一個C#ASP.Net頁面,客戶在郵政局不允許的地址輸入,因爲我們使用UPS運送這些郵件。顧客是富有創造力的人,他們想出創造性的方式來標記P.O.框。測試所有形式的郵政信箱

我們有這種RegEx模式,它主要做我們需要的。

P.O. box 17432 
poSt oFFice box 11111 
box 222 
p0 box 222 
#343 po box 
#po box 343 

不匹配(這是正確的行爲):

(?i)\b[p]*(?:ost)*\.*\s*[o0]*(?:ffice)*\.*\s+?([b]*[o0]*[x]) 

這種模式,我們有文件幾乎所有情況下工作在

1234 Main St (Shouldn't match, but we have it in there for a negative test case.) 

然而,它也不符合這些,它應該:

p0b 222 
POB 1112 

這些樣本實際上是用戶在其慷慨的性質中爲我們提供的值。 ;)

我總是爲了簡化。

+0

刪除評論 – automatic 2011-03-10 18:32:31

+0

他們爲什麼會產生?因爲他們試圖智取系統。當驗證者被絆倒時,它以大的紅色字母表示「沒有郵政信箱」。爲了記錄,我們經常提醒客戶PO郵箱是不允許的。 – amber 2011-03-10 18:45:26

回答

19

我認爲這應該是接近你正在尋找:

(?i)\b(?:p(?:ost)?\.?\s*[o0](?:ffice)?\.?\s*b(?:[o0]x)?|b[o0]x) 

的解釋:

(?:    # start non-capturing group 
    p   # match a 'p' 
    (?:ost)?  # optionally match 'ost' 
    \.?   # optionally match a '.' 
    \s*   # match some number of spaces 
    [o0]   # match an 'o' or '0' 
    (?:ffice)? # optionally match 'ffice' 
    \.?   # optionally match a '.' 
    \s*   # match some number of spaces 
    b(?:[o0]x)? # match 'b', 'box', or 'b0x' 
    |    # or 
    b[o0]x  # match 'box' or 'b0x' 
) 
+0

Wondeful!謝謝! – amber 2011-03-10 18:51:44

+2

顯然這個正則表達式得到了像'PSC 001 Box 001'這樣的地址的誤報,這似乎是軍事地址。 – 2016-05-17 12:56:36

+0

我發現這個影響我們的系統的一個小例外,那些使用「POST BOX」的人,對於我們來說這個正則表達式的微小修復捕獲了我們需要的東西(???)\ b(?:p(?:ost)? \??\ s *(?:[o0](?: ffice)?)?\??\ s * b(?:[o0] x)?| b [o0] x)'(這裏是一個[demo ](https://regex101.com/r/5XNdOM/2)) – 2017-09-21 22:04:02

相關問題