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

Question:

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
Asked By: xamcx

||

Answers:

You are looking for the following regular expression:

>>> import re
>>> re.findall('[az(d+)]', 'test[az5]test[az6]test')
['5', '6']
>>> 
Answered By: accdias
import re

txt = "test[az5]test[az6]test"
x = re.findall(r"[az(?P<num>d)]", txt)
print(x)

Output
[‘5’, ‘6’]

Answered By: user19898808
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.