4

I have to restrict APO FPO address for the City. I have done it by using this regular expression

var regExp : RegExp = new RegExp('^[af][ .]?p[ .]?o|[P|p]*(OST|ost)*\.*\s*[O|o|0]*(ffice|FFICE)*\.*\s*[B|b][O|o|0][X|x]','i');

This works when there is only APO, FPO, A.p.o, F.P.O etc. pattern, but it still matches when city is APOPKO which should not happen.

i tried with giving \b after [af][ .]?p[ .]?o but din't work for me. Can any one please help on this

Thanks in advance.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Yogesh C
  • 41
  • 1
  • Could you please provide a sample input string? Try [`^\b([af][ .]?p[ .]?o|[Pp]*(OST|ost)*)\b\.*\s*[Oo0]*(ffice|FFICE)*\.*\s*[Bb][Oo0][Xx]`](https://regex101.com/r/xS1lC3/1) – Wiktor Stribiżew Apr 06 '16 at 07:49
  • "APOPKO" this is the sample input string, the regular expression should match only for "APO" now it matches the above sample string since it starts from APO. – Yogesh C Apr 06 '16 at 09:45
  • The problem is that your alternation group seems incorrect, you match either `^[af][ .]?p[ .]?o` or `[P|p]*(OST|ost)*\.*\s*[O|o|0]*(ffice|FFICE)*\.*\s*[B|b][O|o|0][X|x]`. Note that `|` inside the character classes are treated as literal symbols that is why I suggest removing them in my answer. – Wiktor Stribiżew Apr 06 '16 at 09:48
  • Please see my answer - doesn't it work as you need? Try experimenting with the regex demo: paste your sample strings and see if they match. – Wiktor Stribiżew Apr 06 '16 at 11:32

1 Answers1

2

You can use

^([af][ .]?p[ .]?o|[Pp]*(OST|ost)*)\b\.*\s*[Oo0]*(ffice|FFICE)*\.*\s*[Bb][Oo0][Xx]

See the regex demo

I cleaned up your pattern a bit, but the POI is ^([af][ .]?p[ .]?o|[Pp]*(OST|ost)*)\b:

  • ^ - start of string
  • ( - a group: matches either...
    • [af][ .]?p[ .]?o - apo-like strings: [af] matches either a or f, then [ .]? matches an optional (1 or 0) space or dot, then p matches p, then again the [ .]? subpattern, and o matches o.
    • | - or
    • [Pp]*(OST|ost)*) - matches p or P 0+ times (maybe you meant ? - 1 or 0 times), then either OST or ost, again 0+ times.
  • \b - trailing word boundary
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563