如何通过正则表达式排除邮政信箱 - Regex

4
我尝试了几种方法,但都没有成功。我需要排除信箱地址。我想只需要使用?!包裹一下即可...但是它并没有起作用。你有什么想法吗?
^((?i)[P|p]*(OST|ost)*\.*\s*[O|o|0]*(ffice|FFICE)*\.*\s*[B|b][O|o|0][X|x]\s*(\d.))*$

编辑:抱歉,这就是我想要的。

例如:当输入为“P.O. BOX”或“Post Office”时,我需要正则表达式为false。当输入为7821 Test Street时,我需要正则表达式为true。

我正在尝试在一个ASP.net MVC项目中使用它。

/// <summary>
/// Regex for street fields
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple =     false)]
public class StreetAddressAttribute : RegularExpressionAttribute, IClientValidatable
{
/// <summary>
/// Regular expression validation for street field
/// </summary>
public StreetAddressAttribute()
  : base(@"^(?!(?i)[P|p]*(OST|ost)*\.*\s*[O|o|0]*(ffice|FFICE)*\.*\s*[B|b][O|o|0][X|x]\s*(\d.)*)$")
{
}

 /// <summary>
 /// Client side validation
 /// </summary>
 /// <param name="metadata">Modelmetadata</param>
 /// <param name="context">ControllerContext</param>
 /// <returns>Client-side validation rules</returns>
 public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata    metadata, ControllerContext context)
 {
   yield return new ModelClientValidationRule { ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()), ValidationType = "streetaddress" };
 }
}

感谢您的帮助。

2
你能用现实世界的术语解释一下你要匹配的可能值是什么吗? - Mike Brant
您是否要排除所有邮政信箱,甚至是 APO 箱(海外美国军用信箱)? - jle
2
我不会使用正则表达式(因为这只是增加了一个新问题)。我认为更简单的“字符串包含任何'po box'、'p.o. box'、'post office box'等”更好。 - Dai
为什么不匹配一个邮政信箱,然后否定返回值? - Matt
我可以尝试重新考虑整个事情。然而,我目前无法否定返回值,因为正则表达式只是作为属性发送到浏览器中:data-val-regex-pattern="^(?!(?i)[P|p](OST|ost).\s[O|o|0](ffice|FFICE).\s[B|b][O|o|0][X|x]\s*(\d.)*)$" - Ricka
像128号邮政信箱这样的地址是否也包含在内?@MikeBrant是正确的。如果您能告诉我们您将用它做什么,那将非常有帮助。也许如果您能为我们提供更多信息,就会有更好的解决方案。 - Jeffrey
1个回答

7

您的正则表达式存在很多问题,我尝试逐一解决。

  1. In a Character class you don't need a | as an OR. Every character inside is added to the allowed characters list. So doing a [P|p] allows the three characters "P", "p" and "|".

    The correct class would be [Pp]

  2. You use the inline modifier (?i). This makes the following letters all matched case independent. So [Pp] is unnecessary, just p is enough to match the letters "P" and "p".

    Including this first two issues we can change your expression to

     ^(?!(?i)p*(ost)*\.*\s*[Oo0]*(ffice)*\.*\s*b[o0]x\s*(\d.)*)$
    
  3. You made everything except b[o0]x repeatable 0 or more times by the * quantifier. I am quite sure this is not what you want, or do you want to find things like "pppppppostostb0x"?

当输入为“P.O. BOX”或“Post Office”时,假的正则表达式更像这样:
^(?i)(?!p\.?o\.?\sbox|post\soffice).*$

这个正则表达式将匹配每个字符串(由于结尾处的.*),除了以下以这样开头的字符串

  • po box
  • p.o box
  • p.o. box
  • Post Office
  • POST oFfIcE

感谢您清理我的可怕正则表达式! - Ricka

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