如何移除含可变数字的重复子串两侧的单引号?
移除指定动态子串两侧的单引号
问题说明
需要移除起始字符串中重复出现的Highcharts.getOptions().colors[i](其中i为可变数字)两侧的单引号,子串出现次数不固定。示例如下:
- 起始字符串:
starting_string = "{'color':'Highcharts.getOptions().colors[0]','color':'Highcharts.getOptions().colors[1]','color':'Highcharts.getOptions().colors[2]'}"
- 目标字符串:
desired_string = "{'color':Highcharts.getOptions().colors[0],'color':Highcharts.getOptions().colors[1],'color':Highcharts.getOptions().colors[2]}"
解决方案
使用正则表达式匹配目标子串的模式,批量替换掉两侧的单引号。以下是Python实现示例:
代码实现
import re starting_string = "{'color':'Highcharts.getOptions().colors[0]','color':'Highcharts.getOptions().colors[1]','color':'Highcharts.getOptions().colors[2]'}" # 匹配带单引号的目标子串,捕获核心内容 pattern = r"'(Highcharts\.getOptions\(\)\.colors\[\d+\])'" desired_string = re.sub(pattern, r"\1", starting_string) print(desired_string)
代码说明
- 正则表达式
r"'(Highcharts\.getOptions\(\)\.colors\[\d+\])'":- 外层
'匹配子串两侧的单引号 - 括号内的
Highcharts\.getOptions\(\)\.colors\[\d+\]精准匹配Highcharts.getOptions().colors[i]格式(\d+匹配任意位数的数字)
- 外层
re.sub(pattern, r"\1", starting_string)将匹配到的带单引号的内容,替换为捕获到的核心子串,直接去掉两侧单引号
内容的提问来源于stack exchange,提问作者gt1
相关产品推荐
相关产品推荐

