![](/img/trans.png)
[英]Regex in python: word matching if n characters in a row are equal to the pattern
[英]Matching multiple double characters in a word - Python regex
我想识别具有 2 组双字母的单词(在字典结构中)。
我是 Python / regex 的新手——但我已经设法从网站其他地方的一些类似问题中收集到几乎存在的代码。 但这并不完全奏效。
它会拾取两组双打,但前提是它们是相同的字母,如果它们是分开的,它会拾起它们。 我认为 \1 的第二次使用是问题所在,并且仅当它与第一个捕获组的字母相同时才有效。 使用 regex101 可以确认这一点,但不确定如何调整正则表达式以正确匹配。
任何指向我哪里出错的指针都将不胜感激。
#logic being [any letter]* [any letter repeated] [any letter]* [any letter repeated] [any letter]*
import json
import re
dict_data = {"hello":0, "aaoo":0, "aabaa":0, "aaaba":0, "bookkeeping":0, "bookkeeooping":0}
for key in dict_data:
if re.search(r'\b.*(.)\1.*(.)\1.*\b', key):
print("Match found: ", key)
else:
print("No match: ", key)
Output 是:
No match: hello
No match: aaoo #This should work but doesn't
Match found: aabaa #This works
Match found: aaaba #This shouldn't, assume it is matching either 2nd&3rd a or 3rd&4th a
No match: bookkeeping #This should match but doesn't
Match found: bookkeeooping #This works, assume it is matching oo twice
第二个\1
指的是第一个捕获组的值,而您需要使用\2
引用第二个组的值。
re.search
在输入字符串的任何位置搜索正则表达式匹配,您不需要在输入的两端使用.*
。
利用
dict_data = {"hello":0, "aaoo":0, "aabaa":0, "aaaba":0, "bookkeeping":0, "bookkeeooping":0}
for key in dict_data:
if re.search(r'(.)\1.*(.)\2', key):
print("Match found: ", key)
else:
print("No match: ", key)
请参阅Python 演示
No match: hello
Match found: aaoo
Match found: aabaa
No match: aaaba
Match found: bookkeeping
Match found: bookkeeooping
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.