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

Time:08-12

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.

CodePudding user response:

r"(?:[A-Z][0-9]){3}"

CodePudding user response:

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