Python 带字符串的正则表达式:出现两次的字母对
如何使用正则表达式和Python查找字符串中出现两次的字母对 我想遍历字符串列表,找到那些具有重复字母对的字符串,并将它们放入列表中。字母不必相同,这对字母只需重复,尽管字母可以相同 例:Python 带字符串的正则表达式:出现两次的字母对,python,regex,string,list,Python,Regex,String,List,如何使用正则表达式和Python查找字符串中出现两次的字母对 我想遍历字符串列表,找到那些具有重复字母对的字符串,并将它们放入列表中。字母不必相同,这对字母只需重复,尽管字母可以相同 例: xxhgfhdeifhjfrikfoixx-这个有两次xx,所以我想保留这个字符串 kwofhdbugktrkdidhdnbk-这个也会保留,因为hd是重复的 我得到的最好结果就是找到了成对的:([a-z][a-z])\1;([a-z])\2 我需要找到哪些字符串具有重复的对。正则表达式 想象 代码 迭代
xxhgfhdeifhjfrikfoixx
-这个有两次xx
,所以我想保留这个字符串
kwofhdbugktrkdidhdnbk
-这个也会保留,因为hd
是重复的
我得到的最好结果就是找到了成对的:([a-z][a-z])\1;([a-z])\2
我需要找到哪些字符串具有重复的对。正则表达式
想象
代码
迭代所有匹配项
获取字符串中所有正则表达式匹配项的数组
可读
笔记
如果您想明确表示只接受
a-z
字符,可以将\w
切换为[a-z]
。使标题更能描述您的问题。正则表达式总是处理字符串。也许,就我所知,这很接近。但我指的是至少出现两次的任何一对。所以hb或aa,任何东西,只要这对重复。我应该说得更清楚。好吧,更新问题,添加更多细节,输入字符串,预期输出和您的尝试什么味道的正则表达式?什么语言?你试过什么?
(\w{2}).*?(\1)
for match in re.finditer(r"(\w{2}).*?(\1)", subject, re.IGNORECASE):
# match start: match.start()
# match end (exclusive): match.end()
# matched text: match.group()
result = re.findall(r"(\w{2}).*?(\1)", subject, re.IGNORECASE)
# (\w{2}).*?(\1)
#
# Options: Case insensitive; Exact spacing; Dot doesn’t match line breaks; ^$ don’t match at line breaks; Regex syntax only
#
# Match the regex below and capture its match into backreference number 1 «(\w{2})»
# Match a single character that is a “word character” (Unicode; any letter or ideograph, any number, underscore) «\w{2}»
# Exactly 2 times «{2}»
# Match any single character that is NOT a line break character (line feed) «.*?»
# Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
# Match the regex below and capture its match into backreference number 2 «(\1)»
# Match the same text that was most recently matched by capturing group number 1 (case insensitive; fail if the group did not participate in the match so far) «\1»