Extract zip code from string based on conditions (lenght and composition)

Viewed 29

Here's my string

str = "85 ch. Osborne L'Ange-Gardien (Québec) J8L4C1 Canada"

I'm trying to extract J8L4C1

Is there a way to extract a substring based on some conditions (e.g. len(str) = 6 and str = string integer string integer string integer)

Using split wouldn't work since the zip code might be placed somewhere else in the string.

2 Answers

To prevent partial matches, you can use word boundaries \b on the left and the right side, and repeat 3 times a char A-Z followed by a digit \d

\b(?:[A-Z]\d){3}\b

Regex demo

Related