繁体   English   中英

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

[英]regex find substring and replace characters and update whole string

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

我想提取"type of , question" substring并用','替换',' ' '

使用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前后分别替代了一部分,字符串的引用部分中的字符。 请注意,这也适用于单个字符串中的多个引号。

另一种为您提供灵活性的方法是您可以通过两个步骤完成:

  1. 查找引文中包含的所有匹配项,

  2. 在每场比赛中寻找并替换','

例:

# define a pattern that gets you everything inside a double quote
pat = re.compile(r'"[^"]+"')

# re.sub the quote pattern and replace the , in each of those matches.
string = pat.sub(lambda x: x.group(0).replace(',',''), string)

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

这种灵活性允许您根据需要替换尽可能多的',' ,并且一旦找到所有双引号模式,就可以执行其他更改。

split()replace()的组合怎么样?

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

splitted = s.split('"')
print(s.replace(splitted[1], splitted[1].replace(',', '')))

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

注意 :这适用于这种情况,但在双引号外的双引号内具有完全相同的字符串的情况下不起作用。

这个怎么样:

b=""" "hello, howdy". sample text, text then comes "Another, double, quotes" """

for str_match in re.findall(r"\".*?\"",b):
    b = re.sub(str_match,re.sub(r","," ",str_match),b)

print(b)

输出:“你好你好”。 示例文本,文本然后出现“另一个双引号”'

我不完全确定这是否符合您的所有要求,但在您提供的模板上,以下内容将返回您要查找的内容。

result = re.sub('("(?:[^"])*),((?:[^"])*")', r"\1 \2")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM