提问人:user2532296 提问时间:6/2/2023 更新时间:6/2/2023 访问量:41
一组模式的通用/统一正则表达式
common/unified regex for a set of pattern
问:
我正在尝试进行一些文本处理,并且有兴趣知道我是否可以为某种模式提供通用/统一的正则表达式。感兴趣的模式是以 where 结尾的字符串,在 的第二列上有一个数字。一旦正则表达式匹配,我希望将其替换为 .{string}_{i}
i
test.csv
{string}[i]
目前,python脚本对于我明确提及正则表达式模式的字符串按预期工作。我想要一个更通用的正则表达式模式,它将匹配所有字符串,而不是为所有模式编写正则表达式(这是不可扩展的)。{string}_{i}
输入测试 .csv
bom_a14 , COMP_NUM_0
bom_a17 , COMP_NUM_2
bom_a27 , COMP_NUM_11
bom_a35 , FUNC_1V8_OLED_OUT_7
bom_a38 , FUNC_1V8_OLED_OUT_9
bom_a39 , FUNC_1V8_OLED_OUT_10
bom_a46 , CAP_4
bom_a47 , CAP_3
bom_a48 , CAP_6
test.py
import csv
import re
# Match the values in the first column of the second file with the first file's data
with open('test.csv', 'r') as file2:
reader = csv.reader(file2)
for row in reader:
row_1=row[1]
# for matching COMP_NUM_{X}
match_data = re.match(r'([A-Z]+)_([A-Z]+)_(\d+)',row_1.strip())
# for matching FUNC_1V8_OLED_OUT_{X}
match_data2 = re.match(r'([A-Z]+)_([A-Z0-9]+)_([A-Z]+)_([A-Z]+)_(\d+)',row_1.strip())
# if match found, reformat the data
if match_data:
new_row_1 = match_data.group(1) +'_'+ match_data.group(2)+ '[' + match_data.group(3) + ']'
elif match_data2:
new_row_1 = match_data2.group(1) +'_'+ match_data2.group(2)+ '_'+ match_data2.group(3)+'_'+ match_data2.group(4)+'[' + match_data2.group(5) + ']'
else:
new_row_1 = row_1
print new_row_1
输出
COMP_NUM[0]
COMP_NUM[2]
COMP_NUM[11]
FUNC_1V8_OLED_OUT[7]
FUNC_1V8_OLED_OUT[9]
FUNC_1V8_OLED_OUT[10]
CAP_4
CAP_3
CAP_6
预期输出
COMP_NUM[0]
COMP_NUM[2]
COMP_NUM[11]
FUNC_1V8_OLED_OUT[7]
FUNC_1V8_OLED_OUT[9]
FUNC_1V8_OLED_OUT[10]
CAP[4]
CAP[3]
CAP[6]
答:
1赞
Timeless
6/2/2023
#1
我会使用具有单个通用模式的 sub
:
with open("test.csv", "r") as file2:
for row in csv.reader(file2):
s = re.sub(r"(.+)_(\d+)$", r"\1[\2]", row[-1].strip())
print(s)
正则表达式 : [demo]
输出:
COMP_NUM[0]
COMP_NUM[2]
COMP_NUM[11]
FUNC_1V8_OLED_OUT[7]
FUNC_1V8_OLED_OUT[9]
FUNC_1V8_OLED_OUT[10]
CAP[4]
CAP[3]
CAP[6]
1赞
manu190466
6/2/2023
#2
如果使用 re.search,则正则表达式不必完全匹配字符串,而只需匹配子部分即可。 请注意,您甚至不需要使用 csv 阅读器来实现您想要的内容。
import re
data="""bom_a14 , COMP_NUM_0
bom_a17 , COMP_NUM_2
bom_a27 , COMP_NUM_11
bom_a35 , FUNC_1V8_OLED_OUT_7
bom_a38 , FUNC_1V8_OLED_OUT_9
bom_a39 , FUNC_1V8_OLED_OUT_10
bom_a46 , CAP_4
bom_a47 , CAP_3
bom_a48 , CAP_6"""
for line in data.split('\n'):
match_data = re.search(r'(\w+)_(\d+)',line)
if match_data:
g1,g2=match_data.groups()
print(f"{g1}[{g2}]")
下一个:如何将下划线视为空格提取文档编号
评论