Python:如何在 if 语句中使用 RegEx?

新手上路,请多包涵

我有以下代码查看一个目录中的文件并将包含特定字符串的文件复制到另一个目录中,但我正在尝试使用正则表达式,因为字符串可以是大写和小写或两者的混合。

在我尝试使用 RegEx 之前,这是有效的代码

import os
import re
import shutil

def test():
    os.chdir("C:/Users/David/Desktop/Test/MyFiles")
    files = os.listdir(".")
    os.mkdir("C:/Users/David/Desktop/Test/MyFiles2")
    for x in (files):
        inputFile = open((x), "r")
        content = inputFile.read()
        inputFile.close()
        if ("Hello World" in content)
            shutil.copy(x, "C:/Users/David/Desktop/Test/MyFiles2")

这是我尝试使用 RegEx 时的代码

import os
import re
import shutil

def test2():
    os.chdir("C:/Users/David/Desktop/Test/MyFiles")
    files = os.listdir(".")
    os.mkdir("C:/Users/David/Desktop/Test/MyFiles2")
    regex_txt = "facebook.com"
    for x in (files):
        inputFile = open((x), "r")
        content = inputFile.read()
        inputFile.close()
        regex = re.compile(regex_txt, re.IGNORECASE)

我猜我需要一行类似的代码

if regex = re.compile(regex_txt, re.IGNORECASE) == True

但我似乎无法得到任何工作,如果有人能指出我正确的方向,我将不胜感激。

原文由 user1816467 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 473
2 个回答
import re
if re.match(regex, content):
  blah..

您也可以使用 re.search 取决于您希望它如何匹配。

你可以运行这个例子:

 """
very nice interface to try regexes: https://regex101.com/
"""
# %%
"""Simple if statement with a regex"""
import re

regex = r"\s*Proof.\s*"
contents = ['Proof.\n', '\nProof.\n']
for content in contents:
    assert re.match(regex, content), f'Failed on {content=} with {regex=}'
    if re.match(regex, content):
        print(content)

原文由 aw4lly 发布,翻译遵循 CC BY-SA 4.0 许可协议

if re.search(r'pattern', string):

简单的 if-regex 示例:

 if re.search(r'ing\b', "seeking a great perhaps"):     # any words end with ing?
    print("yes")

复杂的 if-regex 示例(模式检查、提取子字符串、不区分大小写):

 match_object = re.search(r'^OUGHT (.*) BE$', "ought to be", flags=re.IGNORECASE)
if match_object:
    assert "to" == match_object.group(1)     # what's between ought and be?

笔记:

  • 使用 re.search() 不重新匹配。 match 方法 限制在字符串的开头,这是一个 令人困惑 的约定。如果需要,请使用 插入符 明确搜索: re.search(r'^...', ...) (或者在 re.MULTILINE 模式下使用 \A

  • 使用 原始字符串 语法 r'pattern' 作为第一个参数。否则你需要加倍反斜杠,如 re.search('ing\\b', ...)

  • 在这些示例中, '\\b'r'\b' 是一个 特殊序列,表示用于正则表达式目的 的单词边界。不要与 '\b''\x08' 退格键混淆。

  • re.search() 返回 None 如果没有找到任何东西,它总是 falsy

  • re.search() 如果找到任何东西,则返回一个 Match 对象,该对象始终为真。

  • 一个组是在模式括号内匹配的。

  • 组编号从 1 开始。

  • 眼镜

  • 教程

原文由 Bob Stein 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题