简体   繁体   English

如何在Python中搜索特定长度的字母数字子字符串?

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

Say I have a string "ldhjshjds HdAjhdshj4 Hdsshj4 kdskjdshjdsjds" 说我有一个字符串“ 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. 我只想搜索以“ H”开头的子字符串(仅字母数字),但前提是该字符串介于10到20个字符之间。

"HdAjhdshj4" would be a match. “ HdAjhdshj4”将是一个匹配项。 "Hdsshj4" would not. “ Hdsshj4”不会。

Would such a regex be costly on CPU cycles? 这样的正则表达式会在CPU周期上造成高昂的成本吗?

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从内容类型HTML / Text(在Gmail中)搜索python 2.7中可变长度8个字母数字的模式 - How to search for a pattern which is variable length 8 alphanumeric in python 2.7 from content type HTML/Text (in Gmail) 如何在python中搜索子字符串? - How to search substring in python? Python检测字符串是否包含特定长度的子字符串 - Python detect if string contains specific length substring Python Re.Search:如何在两个字符串之间找到 substring,该字符串还必须包含特定的 substring - Python Re.Search: How to find a substring between two strings, that must also contain a specific substring 从python中的字符串中提取字母数字子字符串 - Extracting alphanumeric substring from a string in python 如何在Python中使用Regex搜索文档中的所有字母数字序列? - How to search all the alphanumeric sequences in a document using Regex in Python? 如何在Python中搜索子字符串是否进入二进制文件? - How to search if a substring is into a binary file in Python? Python:如何快速搜索集合中的子字符串? - Python: how to search for a substring in a set the fast way? 如何仅为 Python 中的特定数字字符重新格式化字母数字字符串? - How to reformat an alphanumeric string only for a specific numeric character in Python? 如何使用子字符串python查找特定字符串 - how to find specific string with a substring python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM