Search code examples
pythonstringextract

How to match a word surrounded by a prefix and suffix?


Is there any regex to extract words from text that are surrounded by a certain prefix and suffix?

Example:

test[az5]test[az6]test

I need to extract the numbers surrounded by the prefix [az and the suffix ].

I'm a bit advanced in Python, but not really familiar with regex.

The desired output is:

5
6

Solution

  • You are looking for the following regular expression:

    >>> import re
    >>> re.findall('\[az(\d+)\]', 'test[az5]test[az6]test')
    ['5', '6']
    >>>