我有以下代码,它查看一个目录中的文件,并将包含某个字符串的文件复制到另一个目录中,但我尝试使用正则表达式,因为字符串可以是大写和小写,也可以是两者的混合.
在我尝试使用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")
Run Code Online (Sandbox Code Playgroud)
当我尝试使用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)
Run Code Online (Sandbox Code Playgroud)
我猜我需要一行代码
if regex = re.compile(regex_txt, re.IGNORECASE) == True
Run Code Online (Sandbox Code Playgroud)
但我似乎无法得到任何工作,如果有人能指出我正确的方向,将不胜感激.
aw4*_*lly 84
if re.match(regex, content) is not None:
blah..
Run Code Online (Sandbox Code Playgroud)
您也可以re.search根据您希望的匹配方式使用.
Bob*_*ein 12
if re.search(r'pattern', string): (我总是在这里跌跌撞撞)re.search() (我通常这样结束)一个简单的if-test:
if re.search(r'ing\b', "seeking a great perhaps"): # any words end with ing?
print("yes")
Run Code Online (Sandbox Code Playgroud)
检查模式,提取子字符串,不区分大小写:
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?
Run Code Online (Sandbox Code Playgroud)
笔记:
\A不要使用re.match.匹配限制字符串的开头,如果你问我,这是一个令人困惑的约定.如果你想要一个字符串开始匹配,请使用插入符号或re.search(r'^...', ...)相反,r'pattern'
对第一个参数使用原始字符串语法re.search('ing\\b', ...).否则你需要加倍反斜杠,如\b
Nonere.search()如果找不到任何东西就返回,这总是假的.
if re.search(r'pattern', string):如果找到任何内容,则返回Match对象,这总是很简单.
一个组是括号内的匹配
组编号从1开始
REPL使学习API变得容易.只需运行python,创建一个对象,然后要求help:
$ python
>>> import re
>>> help(re.compile(r''))
Run Code Online (Sandbox Code Playgroud)
在命令行显示,除其他外:
search(...)
search(string[, pos[, endpos]])- >匹配对象或None.扫描字符串以查找匹配项,并返回相应的MatchObject实例.None如果字符串中没有位置匹配则返回.
所以你可以做到
regex = re.compile(regex_txt, re.IGNORECASE)
match = regex.search(content) # From your file reading code.
if match is not None:
# use match
Run Code Online (Sandbox Code Playgroud)
偶然,
regex_txt = "facebook.com"
Run Code Online (Sandbox Code Playgroud)
有一个.匹配任何字符,所以re.compile("facebook.com").search("facebookkcom") is not None是真的因为.匹配任何字符.也许
regex_txt = r"(?i)facebook\.com"
Run Code Online (Sandbox Code Playgroud)
该\.文字匹配"."字符而不是治疗.作为一种特殊的正则表达式运算符.
该r"..."位意味着正则表达式编译器获取转义\.而不是解释它的python解析器.
这(?i)使得正则表达式不区分大小写,re.IGNORECASE但是自包含.
| 归档时间: |
|
| 查看次数: |
124821 次 |
| 最近记录: |