How to find specific pattern in a paragraph in Python?

188 views Asked by At

I want to find a specific pattern in a paragraph. The pattern must contain a-zA-Z and 0-9 and length is 5 or more than 5. How to implement it on Python?

My code is:

str = "I love5 verye mu765ch"
print(re.findall('(?=.*[0-9])(?=.*[a-zA-Z]{5,})',str))

this will return a null.

Expected result like:

love5
mu765ch

the valid pattern is like:

9aacbe
aver23893dk
asdf897
1

There are 1 answers

4
Jan On BEST ANSWER

This is easily done with some programming logic and a simple regex:

import re

string = "I love5 verye mu765ch a123...bbb"

pattern = re.compile(r'(?=\D*\d)(?=[^a-zA-Z]*[a-zA-Z]).{5,}')

interesting = [word for word in string.split() if pattern.match(word)]
print(interesting)

This yields

['love5', 'mu765ch', 'a123...bbb']

See a demo on ideone.com.