Skip to main content
 首页 » 编程设计

Python之匹配变量正则表达式,包括双括号

2024年08月19日44tintown

我有一个 DataFrame 'df' 和一个字符串列表 'l'。我想遍历列表并找到与列表中的字符串匹配的 DataFrame 行。 如果列表元素中没有括号,则以下代码可以正常工作。似乎正则表达式没有正确定义,双括号不知何故没有匹配。

import pandas as pd 
import re 
 
d = {'col1': ['100-(abc)','qwe-100-(abc)', '100-(abc)1',  
              'xyz', 'xyz2', 'zzz'],  
     'col2': ['100', '1001','200', '300', '400', '500']} 
 
df = pd.DataFrame(d) 
 
lst = ['100-(abc)', 'xyz'] 
 
for l in lst: 
    print("======================") 
    pattern = re.compile(r"(" + l + ")$") 
    print(df[df.col1.str.contains(pattern, regex=True)]) 

结果:

====================== 
Empty DataFrame 
Columns: [col1, col2] 
Index: [] 
====================== 
  col1 col2 
3  xyz  300 

预期结果:

====================== 
  col1           col2 
0  100-(abc)     100 
1  qwe-100-(abc) 1001 
 
====================== 
  col1 col2 
3  xyz  300 

请您参考如下方法:

你需要明白:

Regex have some reserve certain characters for special use the opening parenthesis (, the closing parenthesis ), are one of them.

如果您想将这些字符中的任何一个用作正则表达式中的文字,则需要使用反斜杠对它们进行转义。如果要匹配 1+1=2,正确的正则表达式是 1\+1=2。否则,加号具有特殊含义。 与 parenthesis 相同,如果你想匹配 (abc) 你必须做 \(abc\)

import pandas as pd 
import re 
 
d = {'col1': ['100-(abc)','qwe-100-(abc)', '100-(abc)1', 
              'xyz', 'xyz2', 'zzz'], 
     'col2': ['100', '1001','200', '300', '400', '500']} 
 
df = pd.DataFrame(d) 
 
lst = ['100-(abc)', 'xyz'] 
 
 
for l in lst: 
    print("======================") 
    if '(' in l: 
        match=l.replace('(','\(').replace(')','\)') 
        pattern = r"(" + match + ")$" 
        print(df[df.col1.str.contains(pattern, regex=True)]) 
    else: 
        pattern = r"(" + l + ")$" 
        print(df[df.col1.str.contains(pattern, regex=True)]) 

输出:

            col1  col2 
0      100-(abc)   100 
1  qwe-100-(abc)  1001 
====================== 
  col1 col2 
3  xyz  300