首页 > 解决方案 > 为什么我的正则表达式可以在 regexr.com 上运行,但从命令行运行时会抛出错误?

问题描述

我需要用正则表达式解决两个问题来定位文件路径。

1) 主要问题:我收到一条我不理解的错误消息。2)在我改变一些小东西之前,脚本会运行,但正则表达式搜索什么也没返回。

在匹配正确位置的 regexr.com 和 pythex.org 中测试时,正则表达式确实有效。当我从命令行运行它时它不起作用。

这是我的目标正则表达式:

('([a-zA-Z]:\\)([a-zA-Z0-9 ]*\\)*([a-zA-Z0-9 ]*\/)*([a-zA-Z0-9 ])*(\.[a-zA-Z]*)*'

这是其中使用的代码:

import os
import re

#run script from directory the script is in - place it in the dir being processed
start_path = os.path.dirname(os.path.realpath(__file__))
metadata_path = start_path + "\Metadata"

#change directory to the metadata folder where email.txt is
try:
    os.chdir(metadata_path)
except: print ('Could not change directory. Please try again.')

with open("email.txt", 'r', encoding = 'utf-8') as file:
    all_lines = file.readlines()
    no_header = all_lines[5:] #remove the header lines from email.txt
new_lines =[]
all_files=[]
unique_files =[]
for i in range(len(no_header)):#remove square charcter
    new_lines.append(re.sub('\S\-\d+', '',no_header[i]))

for i in range(len(new_lines)):#capture all the names of files containing personal emails
    test = re.search('([a-zA-Z]:\\)([a-zA-Z0-9 ]*\\)*([a-zA-Z0-9 ]*\/)*([a-    
    zA-Z0-9 ])*(\.[a-zA-Z]*)*',new_lines[i]) 
    print (test)

我收到错误消息 're.error: missing ), unterminated subpattern at position 0'

据我所知,它有一个偶数的括号,它们似乎相互匹配。我猜这与我如何在模式中对事物进行分组有关。

至于它什么都不返回,我是否错过了在线测试人员没有捕捉到的特定于 python 的规则?

谢谢!

标签: pythonregex

解决方案


我的猜测是它可能r在表达式中的某处丢失或括号:

测试

import re

regex = r"([a-zA-Z]:\\)([a-zA-Z0-9 ]*\\)*([a-zA-Z0-9 ]*\/)*([a-zA-Z0-9 ])*(\.[a-zA-Z]*)*"

test_str = "a:\\a\\a/a.a"

print(re.search(regex, test_str))

该表达式在regex101.com的右上角面板上进行了说明,如果您希望探索/简化/修改它,并且在此链接中,您可以查看它如何与一些示例输入匹配,如果您愿意的话。

代码

import os
import re

#run script from directory the script is in - place it in the dir being processed
start_path = os.path.dirname(os.path.realpath(__file__))
metadata_path = start_path + "\Metadata"

#change directory to the metadata folder where email.txt is
try:
    os.chdir(metadata_path)
except: print ('Could not change directory. Please try again.')

with open("email.txt", 'r', encoding = 'utf-8') as file:
    all_lines = file.readlines()
    no_header = all_lines[5:] #remove the header lines from email.txt
new_lines =[]
all_files=[]
unique_files =[]
for i in range(len(no_header)):#remove square charcter
    new_lines.append(re.sub(r'\S\-\d+', '',no_header[i]))

for i in range(len(new_lines)):#capture all the names of files containing personal emails
    test = re.search(r'([a-zA-Z]:\\)([a-zA-Z0-9 ]*\\)*([a-zA-Z0-9 ]*\/)*([a-    
    zA-Z0-9 ])*(\.[a-zA-Z]*)*',new_lines[i]) 
    print (test)

推荐阅读