重构地址验证的正则表达式。

4
我在我的Angular应用程序中有以下用于邮政地址验证的正则表达式。
const regx ='\\b([p]*(ost)*\\.*\\s*[o|0]*(ffice)*\\.*\\s*b[o|0]x)\\b'
我只想让此正则表达式通过以下匹配列表:
1. P.O.Box 2. pobox 3. post office box 4. 1234 post office box street 5. 123 postal office box
但它也匹配以下不匹配列表:
1. box 2. BOX 3. poor box

etc.,

我该如何修改这个正则表达式,使其不匹配“不匹配列表”中的内容?另外,我希望我的正则表达式能够升级以匹配邮政信箱或邮政箱等内容。有什么建议吗?

2个回答

5

根据您提供的示例,请尝试以下正则表达式。这里是用于该正则表达式的在线演示

^(?:[0-9]*\s*[pP](?:\.O\.|o)(?:st(?:al)?\soffice\s)*[bB]ox(?:\sstreet)?)$

说明: 为上述正则表达式添加详细说明。

^(?:                 ##Starting 1 non-capturing group from starting of the value.
  [0-9]*\s*          ##Matching 0 or more digits followed by 0 or more spaces.
  [pP]               ##Matching p OR P here.
  (?:\.O\.|o)        ##In a non-capturing group matching .O. OR o here.
  (?:st(?:al)?\soffice\s)*  ##In a non-capturing group matching st followed by spaces followed by office followed by spaces and keeping this non-capturing group Optional.
  [bB]ox             ##Matching b OR B followed by ox here.
  (?:\sstreet)?      ##In a non-capturing group matching space street and keep this optional.
)$                   ##Closing non-capturing group at the end of the value here.

我刚刚编辑了我的问题以消除一些混淆。但是字符串可以以任何字符或数字开头或结尾,例如1234 po box street。 - Brooklyn99
@Brooklyn99,好的,正则表达式已成功更新。稍后我会编辑一下以便解释清楚。 - RavinderSingh13
1
@Brooklyn99,正则表达式的解释已经成功更新了,干杯。 - RavinderSingh13

4

这里是另一种变体,应该适合你的需求:

/^(?:\d+\s*)?p\.?o\.?(?:st(?:al)?)?(?:\s+office)?\s*b(?:ox|in)\b.*/gmi

由于我们在此处使用了忽略大小写修饰符,因此我们可以在正则表达式中使用所有小写字母。 正则表达式演示

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接