python - 为什么我的正则表达式可以在 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 的规则?
谢谢!
解决方案
我的猜测是它可能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)
推荐阅读
- google-bigquery - 在聚簇表 BigQuery 上安排插入
- r - 在 Mac OS 上安装没有管理员的 R
- excel - 如何根据特定条件突出显示散点图(Excel)中的特定数据点?
- python - 检查单词是否在一个系列中,然后从字符串中删除它
- android-memory - android 如何动态获取应用程序的内存使用情况,例如使用 android studio profiler 显示
- sass - 使用包含斜杠和冒号的属性选择器时出现重复的 CSS 排除
- android - 如何处理在 android kotlin 中上传文件的改造套接字超时?
- python - 将包含字符串和 int 对象的列表转换为字节数组以进行套接字通信
- excel - 将行从一张纸复制到另一张带有多个表格的表格
- java - 使用未更新的 JButton 更改 JFrame 背景颜色