我有一个Latex文件,其中标记了很多文本\red{}
,但其中也可能有括号\red{}
,例如\red{here is \underline{underlined} text}
。我想删除红色,并在进行一些谷歌搜索后写了以下python脚本:
import os, re, sys
#Start program in terminal with
#python RedRemover.py filename
#sys.argv[1] then has the value filename
ifn = sys.argv[1]
#Open file and read it
f = open(ifn, "r")
c = f.read()
#The whole file content is now stored in the string c
#Remove occurences of \red{...} in c
c=re.sub(r'\\red\{(?:[^\}|]*\|)?([^\}|]*)\}', r'\1', c)
#Write c into new file
Nf=open("RedRemoved_"+ifn,"w")
Nf.write(c)
f.close()
Nf.close()
但这会转换
\ red {这里是\ underline {下划线}文字}
到
这是\ underline {带下划线的文字}
这不是我想要的。我想
这是\ underline {下划线}文字
由于re模块不支持递归,因此无法将不确定级别的嵌套括号与re模块匹配。为了解决这个问题,您可以使用新的regex模块:
import regex
c = r'\red{here is \underline{underlined} text}'
c = regex.sub(r'\\red({((?>[^{}]+|(?1))*)})', r'\2', c)
(?1)
对捕获组的递归调用在哪里1。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句