You need to enable JavaScript to run this app. 如何在pandas DataFrame中使用re.search匹配包含[]的字符串
优惠活动
大模型
产品
解决方案
定价
更多

如何在pandas DataFrame中使用re.search匹配包含[]的字符串

问题原因

[和]属于正则语法中的特殊字符,用来标记字符集范围,正则语法不允许出现空字符集[],所以你把包含[]的字符串直接作为正则模式传入re.search时,会触发语法错误。

解决方法

如果你需要匹配的是字面文本,不需要用到正则的特殊匹配规则,只要用re.escape()处理待匹配的模式字符串,自动转义所有正则特殊字符即可。

修改后的代码如下:

import pandas as pd
import re

df = pd.DataFrame([['a[]'],['a[] foo'],['a[] foo \n bar']],columns = ['a'])

txt = 'a[] foo \n bar'

def Function(x):
    # 用re.escape转义模式里的所有正则特殊字符
    if re.search(re.escape(x), txt):
        return 'Match'
    else:
        return 'Nomatch'

df['match'] = df['a'].apply(Function)

运行修改后的代码,得到的df['match']列会全部返回Match,符合预期。

补充优化方案

如果你的匹配逻辑完全不需要正则功能,只是判断文本包含关系,可以直接用Python原生的in运算符,性能更高也不会有特殊字符问题:

def Function(x):
    return 'Match' if x in txt else 'Nomatch'

内容的提问来源于stack exchange,提问作者aaaaa0a

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 18:15:05