如何仅移除字符串中引号后方紧跟的数字?
移除引号后紧跟数字的处理方案
需求说明
需要处理类似这样的字符串:
the "cow"1 jumped "over"2 the moon and the "spoon"3... this happened 123 times
只删除双引号"紧跟的数字,保留其他位置的数字,最终得到:
the "cow" jumped "over" the moon and the "spoon"... this happened 123 times
解决方案:正则表达式替换
利用正则精准匹配引号后的数字,替换为空即可,不影响其他数字。
Python 示例代码
import re original_str = 'the "cow"1 jumped "over"2 the moon and the "spoon"3... this happened 123 times' result = re.sub(r'(?<=")\d+', '', original_str) print(result)
JavaScript 示例代码
const originalStr = 'the "cow"1 jumped "over"2 the moon and the "spoon"3... this happened 123 times'; const result = originalStr.replace(/"(\d+)/g, '"'); console.log(result);
正则逻辑说明
- 对于Python中的
(?<=")\d+:(?<="):正向后顾断言,确保当前匹配的数字前面是双引号\d+:匹配一个或多个连续数字
- 对于JavaScript中的
"(\d+):- 匹配双引号加后续的连续数字,替换时只保留双引号,去掉捕获的数字部分
两种写法都能精准实现需求,不会误删其他位置的数字(比如示例里的123)。
内容的提问来源于stack exchange,提问作者timothy.s.lau
相关产品推荐
相关产品推荐

