I have a regular expression for checking whether a string is zip/postal code or not. But I would really like to also to be able to extract that from a full address (or, if possible, any string).
Here is my current regular expression:
/^((\d{5}-\d{4})|(\d{5})|([a-zA-Z]\d[a-zA-Z]\s\d[a-zA-Z]\d)|([a-zA-Z]\d[a-zA-Z]\d[a-zA-Z]\d))$/
If necessary I'm willing to settle for a function (I'm checking with PHP) but I'd rather the regexp do the work if possible.
preg_match
, which I assume you're already using when you're checking a string against your regular expression, also gives you back the actual text that matched your pattern.
preg_match($regex, $input, $matches);
echo $matches[0];
The third argument is filled with the results of trying to match the regex against your input. $matches[0]
will contain text that matched the whole pattern, while higher indexes will contain text that matched against capturing subpatterns (the parts of the pattern enclosed in parentheses).
However, in your case, you've enclosed your pattern with the start-of-input ^
and end-of-input $
characters, which means that any matches must include the entire input string (or an entire line in multiline mode). You'd have to get rid of the ^
and $
before trying to use this pattern to extract a postal code from a larger string.