6

如何在 Python 中匹配重叠字符串?

 9 months ago
source link: https://www.jdon.com/70891.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

如何在 Python 中匹配重叠字符串?

正则表达式是一种强大的字符串匹配工具。然而,标准的 regex 模式可能无法捕获重叠匹配。

这时,正向前瞻lookahead (?=) 就派上用场了,因为它不会 "消耗 "字符,从而允许多重匹配:

下面是一个使用 re 模块的示例:

import re

def find_overlapping_strings(pattern, text):
    matches = re.finditer(f'(?=({pattern}))', text)
    return [match.group(1) for match in matches]

# Example usage
pattern = 'overlapping'
text = 'overlappingstringsarehardtofindoverlapping'
result = find_overlapping_strings(pattern, text)
print(result)

在本例中,函数 find_overlapping_strings 将模式和文本作为输入。它使用带有正向前瞻性的正则表达式((?=...))查找文本中重叠出现的模式。finditer 方法用于查找所有匹配项,结果是重叠字符串列表。

请注意,这种方法适用于固定模式。如果您的模式包含在正则表达式中具有特殊含义的特殊字符,您可能需要使用 re.escape(pattern) 对其进行转义。

请记住,这种方法对于大型文本或模式可能不是最有效的,在某些情况下,您可能需要考虑使用其他算法来获得更优化的解决方案。

regex 模块
另外一种选项是使用 `regex` 模块,regex的语法与 re 模块类似,但 regex 模块默认支持重叠匹配。:

import regex 
regex.findall(r'cat|at', 'The catapult', overlapped=True)

输出['cat', 'at']

使用 overlapped=True 参数查找文本中出现的所有模式,允许重叠匹配。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK