본문 바로가기
파이썬

파이썬 Python : if 문에서 RegEx를 사용하는 방법은 무엇입니까?

by º기록 2021. 1. 29.
반응형

한 디렉터리의 파일을 살펴보고 특정 문자열이 포함 된 파일을 다른 디렉터리로 복사하는 다음 코드가 있지만 문자열이 대문자와 소문자 또는 둘 다일 수 있으므로 정규식을 사용하려고합니다.

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

그러나 누군가가 나를 올바른 방향으로 안내 할 수 있다면 고맙게 생각할 것입니다.

 

해결 방법

 

if re.match(regex, content) is not None:
  blah..

일치하는 방식에 따라 re.search 를 사용할 수도 있습니다.

 

참조 페이지 https://stackoverflow.com/questions/14225608

 

 

반응형

댓글