如何在“((VERB)”之前添加空格,前提是它前面没有空格或字符串开头?

问题描述 投票:0回答:2
import re

#input string example:
input_text = "((VERB)ayudar a nosotros) ár((VERB)ayudar a nosotros) Los computadores pueden ((VERB)ayudar a nosotros)"


#this give me a raise error("look-behind requires fixed-width pattern") re.error: look-behind requires fixed-width pattern
#input_text = re.sub(r"(?<!^|\s)\(\(VERB\)", " ((VERB)", input_text)

#and this other option simply places a space in front of all ((VERB) ) 
# without caring if there is a space or the beginning of the string in front 
input_text = re.sub(r"(^|\s)\(\(VERB\)", lambda match: match.group(1) + "((VERB)", input_text)

print(repr(input_text)) # --> output

我尝试过使用

(^|\s)
,因为它是一个捕获组,用于查找字符串的开头
^
或模式
"((VERB)"
之前的空格。另一个模式选项可能是使用非捕获组
(?:|)
或更好地仍然使用上下文限制器,如后视
(?<!^|\s)

这是运行此脚本时应该得到的输出:

"((VERB)ayudar a nosotros) ár ((VERB)ayudar a nosotros) Los computadores pueden ((VERB)ayudar a nosotros)"
python python-3.x regex string regex-lookarounds
2个回答
2
投票

您可以在左侧断言一个非空白字符:

(?<=\S)\(\(VERB\)

正则表达式演示 | Python演示

在替换中使用空格后跟完整匹配

r" \g<0>"

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" \g<0>", input_text)
print(input_text)

输出

((VERB)ayudar a nosotros) ár ((VERB)ayudar a nosotros) Los computadores pueden ((VERB)ayudar a nosotros)

2
投票

使用lookbehind的替代方法是匹配除

((VERB)
之前的空格之外的任何字符:

([^\s])(\(\(VERB\))

替换为

\1 \2
  • (
    - 捕获组 1 的开始
    • [^\s]
      - 匹配不是空格的单个字符
  • )
    - 捕获组 1
  • 结束
  • (
    - 捕获组 2 的开始
    • \(\(VERB\)
      -
      ((VERB)
    • 上的字面匹配
  • )
    - 捕获组 2 结束

演示

© www.soinside.com 2019 - 2024. All rights reserved.