我们有一个 C# ASP.Net 页面,客户可以在该页面中输入邮局地址,因为我们使用 UPS 运送这些元素。客户是有创造力的人,他们会想出创造性的方法来标记 P.O.盒子。
我们有这种 RegEx 模式,它主要满足我们的需求。
(?i)\b[p]*(?:ost)*\.*\s*[o0]*(?:ffice)*\.*\s+?([b]*[o0]*[x])
这种模式几乎适用于我们存档的所有案例:
P.O. box 17432
poSt oFFice box 11111
box 222
p0 box 222
#343 po box
#po box 343
它不匹配(这是正确的行为):
1234 Main St (Shouldn't match, but we have it in there for a negative test case.)
但是,它也不符合这些,它应该:
p0b 222
POB 1112
这些样本实际上是用户慷慨地为我们提供的值(value)。 ;)
我总是追求简化。
最佳答案
我认为这应该接近您要查找的内容:
(?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'
)
关于c# - 测试所有形式的邮政信箱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5263956/