如何仅在((VERB))非开头且无前导空格时为其添加前置空格?
问题:为非开头/非空格前的
((VERB)添加前置空格 需求:仅当字符串中的((VERB)前面不是空格或字符串开头时,在其前方添加一个空格。
示例输入
import re # 输入字符串示例: input_text = "((VERB)ayudar a nosotros) ár((VERB)ayudar a nosotros) Los computadores pueden ((VERB)ayudar a nosotros)" # 此代码会抛出错误("look-behind requires fixed-width pattern")re.error: 后视断言要求固定宽度模式 # input_text = re.sub(r"(?<!^|\\s)\\(\\(VERB\\)", " ((VERB)", input_text) # 此方案会为所有((VERB))前添加空格,不考虑前方是否已有空格或是否为字符串开头 input_text = re.sub(r"(^|\\s)\\(\\(VERB\\)", lambda match: match.group(1) + "((VERB)", input_text) print(repr(input_text)) # --> 输出
之前尝试的问题
- 使用
(?<!^|\s)可变宽度后视断言时,Python的re模块报错,因为它不支持长度不固定的后视匹配(^是零宽度,\s是单字符宽度,属于可变宽度)。 - 用捕获组
(^|\s)匹配开头或空格的方案逻辑错误,无法区分需要添加空格的场景,会无差别处理所有((VERB)。
解决方案
方案1:叠加固定宽度后视断言(全Python版本兼容)
Python允许叠加多个固定宽度的后视断言,我们可以分别判断((VERB)既不在字符串开头,前面也不是空格:
import re input_text = "((VERB)ayudar a nosotros) ár((VERB)ayudar a nosotros) Los computadores pueden ((VERB)ayudar a nosotros)" # 两个固定宽度后视断言组合:排除开头和空格前的情况 input_text = re.sub(r"(?<!^)(?<!\s)\(\(VERB\)", " ((VERB)", input_text) print(repr(input_text))
方案2:匹配前置非空格字符并替换(更直观)
直接匹配((VERB)前面的非空白字符,替换时保留该字符并插入空格:
import re input_text = "((VERB)ayudar a nosotros) ár((VERB)ayudar a nosotros) Los computadores pueden ((VERB)ayudar a nosotros)" # 捕获非空格字符,替换时保留字符并添加空格 input_text = re.sub(r"(\S)\(\(VERB\)", r"\1 ((VERB)", input_text) print(repr(input_text))
期望输出
"((VERB)ayudar a nosotros) ár ((VERB)ayudar a nosotros) Los computadores pueden ((VERB)ayudar a nosotros)"
内容的提问来源于stack exchange,提问作者Matt095
相关产品推荐
相关产品推荐

