gpt4 book ai didi

python - 正则表达式在python括号内的所有出现的字符周围添加空格

转载 作者:行者123 更新时间:2023-11-28 22:20:34 34 4
gpt4 key购买 nike

我的目标是分隔括号之间的破折号。例如:“Mr. Queen(The-American-Detective,EQ),Mr. Holmes(The-British-Detective)”

我想要的结果是

《Mr. Queen(The-American-Detective, EQ),Mr. Holmes(The-British-Detective)》

我的代码是

re.sub(r'(.*)(\(.*)(-)(.*\))(.*)', r'\1\2 \3 \4\5', String)

但是,这段代码似乎只分隔出现在字符串最后一个括号中的最后一个破折号。

它给出的结果是“‘女王先生(美国侦探,EQ),福尔摩斯先生(英国侦探)”

有人可以帮忙吗?我试图通过这里找到;但似乎我的代码应该按我预期的方式工作

最佳答案

此代码通过将其分成两个独立的部分而不是仅依赖于单个正则表达式来完成任务。

  1. 它在字符串 target 中搜索被 (...)
  2. 包围的部分
  3. 然后它使用 replacement functions

这里有解决方案代码:

def expand_dashes(target):
"""
replace all "-" with " - " when they are within ()

target [string] - the original string

return [string] - the replaced string

* note, this function does not work with nested ()
"""
return re.sub(r'(?<=\()(.*?)(?=\))', __helper_func, target)

def __helper_func(match):
"""
a helper function meant to process individual groups
"""
return match.group(0).replace('-', ' - ')

这里我们有演示输出:

>>> x = "Mr. Queen (The-American-Detective, EQ), Mr. Holmes (The-British-Detective)"
>>> expand_dashes(x)
>>> "Mr. Queen (The - American - Detective, EQ), Mr. Holmes (The - British - Detective)"

关于python - 正则表达式在python括号内的所有出现的字符周围添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48848594/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com