gnome32
gnome32

Reputation: 21

How to search for alphanumeric substring of specific length in Python?

Say I have a string "ldhjshjds HdAjhdshj4 Hdsshj4 kdskjdshjdsjds"

I only want to search for substrings (alphanumeric only) starting with "H", but only if the string is between 10-20 characters.

"HdAjhdshj4" would be a match. "Hdsshj4" would not.

Would such a regex be costly on CPU cycles?

Upvotes: 1

Views: 1833

Answers (3)

vks
vks

Reputation: 67968

You can do this using lookarounds.

re.findall(r'(?:^|(?<=\s))H[A-Za-z0-9]{9,19}(?=\s|$)', s)

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

Use negative lookarounds.

re.findall(r'(?<!\S)H[A-Za-z0-9]{9,19}(?!\S)', s)

DEMO

Upvotes: 0

dxdy
dxdy

Reputation: 540

r"\bH[A-Za-z0-9]{9,19}\b" looks for precisely that.

Upvotes: 1

Related Questions