gpt4 book ai didi

python - 正则表达式查找子字符串并替换字符并更新整个字符串

转载 作者:太空宇宙 更新时间:2023-11-03 12:53:16 29 4
gpt4 key购买 nike

来自

string= this is, not good "type of ,question" to ask, on stackoverflow

我想提取 "type of , question" 子字符串并将 ',' 替换为 ' '

使用 re.findall() 会生成 "" 之间的字符列表,使用 re.search 会生成类对象。

使用 re.sub() 它替换了所有 ',' 但我需要它们,除了那些在带双引号的子字符串中。

谁能帮我解决这个问题。

提前致谢!

最佳答案

使用正则表达式捕获组:

import re
s= 'this is, not good "type of ,question" to ask, on stackoverflow'
re.sub(r'(".*?),(.*?")', r'\1\2', s)

输出:

'this is, not good "type of question" to ask, on stackoverflow'

解释:(stuff)在正则表达式中代表捕获组,\1\2分别替换,前后的部分字符串引用部分中的字符。请注意,这也适用于单个字符串中的多个引号。

关于python - 正则表达式查找子字符串并替换字符并更新整个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53397243/

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