2011-03-10 75 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

相关问题