Home > database >  How to match a word surrounded by a prefix and suffix?
How to match a word surrounded by a prefix and suffix?

Time:12-01

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

CodePudding user response:

You are looking for the following regular expression:

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

CodePudding user response:

import re

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

Output ['5', '6']

  • Related