带字符串的正则表达式:出现在

2024-10-02 04:34:33 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在Python中使用regex查找字符串中出现两次的字母对?在

我想遍历一个字符串列表,找到那些有重复字母对的字符串,并将它们放入一个列表中。字母不必相同,两个字母只需重复,尽管字母可以相同。在

例如: xxhgfhdeifhjfrikfoixx-这个有xx两次,所以我想保留这个字符串 kwofhdbugktrkdidhdnbk-这个也会被保留,因为{}是重复的

我得到的最好的结果是找到两对:([a-z][a-z])\1|([a-z])\2

我需要找出哪些字符串有重复的对。在


Tags: 字符串列表字母regexxxxxhgfhdeifhjfrikfoixxkwofhdbugktrkdidhdnbk
1条回答
网友
1楼 · 发布于 2024-10-02 04:34:33

正则表达式

(\w{2}).*?(\1)

https://regex101.com/r/yB3nX6/1

视觉化

Visualisation

代码

迭代所有匹配项

^{pr2}$

获取字符串

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»

注释

如果您想明确只接受a-z字符,可以将\w换成{}。在

相关问题 更多 >

    热门问题