2301_81795815 2024-09-01 16:43 采纳率: 33.3%
浏览 3

re.compile中使用正则表达式

为什么我连用两个正则表达式,结果什么也打印不出来,但是我单独用任意一个正则表达式,符合的结果都可以打出来

img

img

  • 写回答

1条回答 默认 最新

  • 九月镇灵将 2024-09-05 16:53
    关注
    
    import re
    
    
    def recompile(patterns):
        # 将所有模式连接成一个正则表达式
        pattern_str = '|'.join(patterns)
        # 编译正则表达式
        regex = re.compile(pattern_str, re.IGNORECASE)
        return regex
    
    
    # 使用示例
    keywords = ['python', 'example', 'match']
    regex = recompile(keywords)
    
    text = "This is an example of matching Python keywords."
    matches = regex.findall(text)
    print(matches)  # 输出匹配到的关键词列表
    

    参考这个案例,你要实现多个关键词匹配要用"|"把多个表达式隔开,按你的代码那样写两个表达式是直接拼接在一起的得到新的表达式

    img

    评论

报告相同问题?

问题事件

  • 创建了问题 9月1日