python正则表达式删除匹配括号文件

时间:2014-06-03 12:04:16

标签: python regex

我有一个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 {underlined} text}

  

这里是\ underline {underlined text}

这不是我想要的。我想要

  

这里是\ underline {underlined} text

2 个答案:

答案 0 :(得分:6)

您不能将未确定级别的嵌套括号与re模块匹配,因为它不支持递归。要解决此问题,您可以使用new regex module

import regex

c = r'\red{here is \underline{underlined} text}'

c = regex.sub(r'\\red({((?>[^{}]+|(?1))*)})', r'\2', c)

其中(?1)是对捕获组1的递归调用。

答案 1 :(得分:1)

我认为你需要保留curlies,考虑这种情况:\red{\bf test}

import re

c = r'\red{here is \underline{underlined} text} and \red{more}'
d = c 

# this may be less painful and sufficient, and even more correct
c = re.sub(r'\\red\b', r'', c)
print "1ST:", c

# if you want to get rid of the curlies:
d = re.sub(r'\\red{([^{]*(?:{[^}]*}[^}]*)*)}', r'\1', d)
print "2ND:", d

给出:

1ST: {here is \underline{underlined} text} and {more}
2ND: here is \underline{underlined} text and more