Python:如何在 if 语句中使用 RegEx? [英] Python: How to use RegEx in an if statement?

查看:51
本文介绍了Python:如何在 if 语句中使用 RegEx?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following code which looks through the files in one directory and copies files that contain a certain string into another directory, but I am trying to use Regular Expressions as the string could be upper and lowercase or a mix of both.

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

Here is the code that works, before I tried to use RegEx's

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 时的代码

Here is my code when I have tried to use RegEx's

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)

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

Im guessing that I need a line of code that is something like

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

但我似乎什么都做不了,如果有人能指出我正确的方向,我将不胜感激.

But I cant seem to get anything to work, if someone could point me in the right direction it would be appreciated.

推荐答案

if re.match(regex, content):
  blah..

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

You could also use re.search depending on how you want it to match.

这篇关于Python:如何在 if 语句中使用 RegEx?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆