为什么我的正则表达式不能处理str.contains?

2024-09-22 14:27:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个非常简单的搜索字符串。我在找一家叫“Lidl”的商店

我的数据帧:

  term_location  amount
0          Lidl    2.28
1          Lidl   16.97
2          Lidl    2.28
3          Lidl   16.97
4          Lidl   16.97
5          Lidl   16.97
6          Lidl   16.97
7          Lidl   16.97
8          Lidl   16.97
9          Lidl   16.97

这里我正在搜索Lidl的正则表达式版本:

r = r'\blidl\b'

r = re.compile(r)


df[df.term_location.str.contains(r,re.IGNORECASE,na=False)]

这将返回一个空的数据帧

但是,如果我只是将简单字符串放在str.contains()中,它就工作了,并且我得到了返回的LIDL的数据帧:

df[df.term_location.str.contains('lidl',case=False,na=False)]

我希望能够使用regex,因为我还有一些条件要构建到查询中

发生了什么事?我想不出来

pd.DataFrame.from_dict()练习数据帧:

{'term_location': {0: 'Lidl',
  1: 'Lidl',
  2: 'Lidl',
  3: 'Lidl',
  4: 'Lidl',
  5: 'Lidl',
  6: 'Lidl',
  7: 'Lidl',
  8: 'Lidl',
  9: 'Lidl'},
 'amount': {0: 2.28,
  1: 16.97,
  2: 2.28,
  3: 16.97,
  4: 16.97,
  5: 16.97,
  6: 16.97,
  7: 16.97,
  8: 16.97,
  9: 16.97}}

Tags: 数据字符串版本refalsedflocationamount
2条回答

您的正则表达式无法工作,因为您正在尝试完全匹配单词“lidl”(小写)

您应该将单词的第一个字符改为大写:

re.compile(r"\bLidl\b")

或者使用re.IGNORECASE标志来匹配单词,而不管其大小写:

re.compile(r"\blidl\b", re.IGNORECASE)

请记住\b试图匹配文本开头的单词。例如,“_Lidl”与上面的任何正则表达式都不匹配

使用字符串文字作为模式参数,它将被解析为正则表达式:

df[df.term_location.str.contains(r'\blidl\b',case=False,na=False)]
                                   ^^^^^^^^^ 

case=False的作用与re.IGNORECASE相同

或者,使用(?i)

df[df.term_location.str.contains(r'(?i)\blidl\b',na=False)]

相关问题 更多 >