以所有形式测试邮政信箱

amb*_*ber 5 c# regex validation

我们有一个C#ASP.Net页面,当我们使用UPS运送这些物品时,客户进入不允许邮局的地址.客户是富有创造力的人,他们提出了标记邮政信箱的创造性方法.

我们有这种RegEx模式,它主要做我们需要的.

(?i)\b[p]*(?:ost)*\.*\s*[o0]*(?:ffice)*\.*\s+?([b]*[o0]*[x])
Run Code Online (Sandbox Code Playgroud)

这种模式几乎适用于我们存档的每一种情况:

P.O. box 17432
poSt oFFice box 11111
box 222
p0 box 222
#343 po box 
#po box 343
Run Code Online (Sandbox Code Playgroud)

它不匹配(这是正确的行为):

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

但是,它也不符合这些,它应该:

p0b 222
POB 1112
Run Code Online (Sandbox Code Playgroud)

这些样本实际上是用户具有的慷慨性,为我们提供的价值.;)

我总是想要简化.

And*_*ark 21

我认为这应该接近你想要的:

(?i)\b(?:p(?:ost)?\.?\s*[o0](?:ffice)?\.?\s*b(?:[o0]x)?|b[o0]x)
Run Code Online (Sandbox Code Playgroud)

说明:

(?:              # 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'
)
Run Code Online (Sandbox Code Playgroud)

  • 显然这个正则表达式对于像'PSC 001 Box 001'这样的地址有误报,这个地址似乎是一个军事地址. (3认同)