简体   繁体   中英

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?

r"\\bH[A-Za-z0-9]{9,19}\\b"正是在寻找。

Use negative lookarounds.

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

DEMO

您可以使用lookarounds来做到这一点。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM