-1

I have Regualar expression for Postal Codes

 [ABCEGHJKLMNPRSTVXYabceghjklmnprstvxy]{1}\d{1}[A-Za-z]-{1} *\d{1}[A-Za-z]{1}\d{1}|[ABCEGHJKLMNPRSTVXYabceghjklmnprstvxy]{1}\d{1}[A-Za-z]{1} *\d{1}[A-Za-z]{1}\d{1}

This works fine.

But I want only Postal codes that starts from "H" character.

For example: H2X 1X8

But the issue is that this regular expression for those postal codes as well which does not start with "H"

e.g j4k1a4

Suggest me, how to modify this regular expression so that It can work for only postal codes starting with "H" character.

I apreciate any response.

Thanks

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Maria
  • 149
  • 1
  • 3
  • 11

2 Answers2

2

Try this

^[Hh]{1}\d{1}[A-Za-z]-{1} *\d{1}[A-Za-z]{1}\d{1}|^[Hh]{1}\d{1}[A-Za-z]{1} *\d{1}[A-Za-z]{1}\d{1}

Also see this

If the string you are trying to match is not in the starting of the line you can use below regex

[Hh]{1}\d{1}[A-Za-z]-{1} *\d{1}[A-Za-z]{1}\d{1}|[Hh]{1}\d{1}[A-Za-z]{1} *\d{1}[A-Za-z]{1}\d{1}

you can test with different inputs here

Community
  • 1
  • 1
g4ur4v
  • 3,210
  • 5
  • 32
  • 57
  • Thank you so much for your response. It seems good. But It is not working in php for my string: – Maria Sep 07 '14 at 10:46
  • I added PHP code which I used with yoru regular expression. It did not extract postal code from it. Please review it and suggest me that how it can be fixed. – Maria Sep 07 '14 at 10:48
  • 1
    this works `` – g4ur4v Sep 07 '14 at 10:59
1

You can simplify your regex to:

\b(?i)h\d[a-z]-? *\d[a-z]\d\b

where (?i) means case insensitive.

Toto
  • 89,455
  • 62
  • 89
  • 125
  • 1
    @Maria: How did you test it? This regex is virtually identical to the one I came up with, and it seems to work: [`'/\bH\d[A-Z][- ]?\d[A-Z]\d\b/i'`](http://ideone.com/JMyiny) – Alan Moore Sep 07 '14 at 12:19
  • @Maria: Could you show an example that doesn't match? – Toto Sep 08 '14 at 06:54