【问题标题】:Python: How to remove commas inside parentheses? [duplicate]Python:如何删除括号内的逗号? [复制]
【发布时间】: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


【解决方案1】:
import re

data = "John Doe, model (dell, 24-inch)"

def replace(g):
    return g.group(0).replace(',', '')

print(re.sub(r'\(.*?\)', replace, data))

打印:

John Doe, model (dell 24-inch)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-13
    • 2016-04-29
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多