How to change PO BOX - Regex

I tried several things, could not get it to work. I need to exclude PO Boxes. I thought I just had to wrap it?! .. but it doesn't work. Any thoughts?

^((?i)[P|p]*(OST|ost)*\.*\s*[O|o|0]*(ffice|FFICE)*\.*\s*[B|b][O|o|0][X|x]\s*(\d.))*$ 

EDIT: Sorry, this is what I'm looking for.

Example: when entering "PO BOX" or "Post Office", I need regex to be false. When the input is 7821 Test street, I need the regular expression to be true.

I am trying to use it in an ASP.net MVC project

 /// <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" }; } } 

thanks for the help

+4
source share
1 answer

There are so many problems in your regex, I'm trying to address one by one

  • In the character class you do not need | like OR. Each character inside is added to the list of allowed characters. Thus, [P|p] allows you to use the three characters "P", "p" and "|".

    The correct class will be [Pp]

  • You are using the built-in modifier (?i) . This makes the following letters inappropriate. Therefore [Pp] not necessary, just p enough to match the letters "P" and "p".

    Including these first two questions, we can change your expression to

     ^(?!(?i)p*(ost)*\.*\s*[Oo0]*(ffice)*\.*\s*b[o0]x\s*(\d.)*)$ 
  • You have done everything except b[o0]x repeated 0 or more times by the quantifier * . I'm sure this is not what you need, or do you want to find things like "pppppppostostb0x"?

A regular expression that is false when typing "PO BOX" or "Post Office" looks something like this:

 ^(?i)(?!p\.?o\.?\sbox|post\soffice).*$ 

This regex will match every line (due to .* At the end), with the exception of lines that start as follows:

  • po box
  • po box
  • orally. box
  • Post office
  • POST oFfIcE
+4
source

Source: https://habr.com/ru/post/1482458/


All Articles