【发布时间】:2018-07-17 21:57:13
【问题描述】:
我正在尝试使用正则表达式从字符串中删除逗号,但前提是逗号在括号内。之前没有找到类似的 Python 问题答案。
示例字符串:
John Doe, model (dell, 24-inch)
期望的输出:
John Doe, model (dell 24-inch)
【问题讨论】:
-
正确答案是stackoverflow.com/a/50994231/3832970接受的答案是错误的。
-
这似乎有效:
re.sub(", (?=[^(]*\\))"," ", str)有什么原因会失败吗? -
当然,这里 - regex101.com/r/KtXk78/1。您不能仅使用前瞻,因为它不能确保匹配在 inside 括号内。
-
啊,我明白了。谢谢!
-
不要使用仅受 PyPi 支持的正则表达式。试试
pd_series.str.replace(r'\([^()]*\)', lambda x: x.group().replace(",", ""))或pd_series.apply(lambda row: re.sub(r'\([^()]*\)', lambda x: x.group().replace(",", ""), row))
标签: python regex string replace pattern-matching