Python RegEx嵌套搜索和替换

时间:2011-10-04 16:41:35

标签: python regex replace

我需要进行RegEx搜索并替换在引用块内找到的所有逗号 即

"thing1,blah","thing2,blah","thing3,blah",thing4  

需要成为

"thing1\,blah","thing2\,blah","thing3\,blah",thing4  

我的代码:

inFile  = open(inFileName,'r')
inFileRl = inFile.readlines()
inFile.close()

p = re.compile(r'["]([^"]*)["]')
for line in inFileRl:
    pg = p.search(line)
    # found comment block
    if pg:
        q  = re.compile(r'[^\\],')
        # found comma within comment block
        qg = q.search(pg.group(0))
        if qg:
            # Here I want to reconstitute the line and print it with the replaced text
            #print re.sub(r'([^\\])\,',r'\1\,',pg.group(0))

我需要根据RegEx过滤掉我想要的列,进一步过滤,
然后进行RegEx替换,然后重新构建回来。

我怎样才能在Python中执行此操作?

5 个答案:

答案 0 :(得分:3)

csv模块非常适合解析默认方言中忽略带引号的逗号中的csv.reader这样的数据。 csv.writer由于逗号的存在而重新引用引号。我使用StringIO为字符串提供了类似接口的文件。

import csv
import StringIO

s = '''"thing1,blah","thing2,blah","thing3,blah"
"thing4,blah","thing5,blah","thing6,blah"'''
source = StringIO.StringIO(s)
dest = StringIO.StringIO()
rdr = csv.reader(source)
wtr = csv.writer(dest)
for row in rdr:
    wtr.writerow([item.replace('\\,',',').replace(',','\\,') for item in row])
print dest.getvalue()

结果:

"thing1\,blah","thing2\,blah","thing3\,blah"
"thing4\,blah","thing5\,blah","thing6\,blah"

答案 1 :(得分:1)

一般编辑

"thing1\\,blah","thing2\\,blah","thing3\\,blah",thing4   

在问题中,现在它不再存在了。

此外,我没有评论r'[^\\],'

所以,我完全重写了我的答案。

"thing1,blah","thing2,blah","thing3,blah",thing4               

"thing1\,blah","thing2\,blah","thing3\,blah",thing4

显示字符串(我猜)

import re


ss = '"thing1,blah","thing2,blah","thing3\,blah",thing4 '

regx = re.compile('"[^"]*"')

def repl(mat, ri = re.compile('(?<!\\\\),') ):
    return ri.sub('\\\\',mat.group())

print ss
print repr(ss)
print
print      regx.sub(repl, ss)
print repr(regx.sub(repl, ss))

结果

"thing1,blah","thing2,blah","thing3\,blah",thing4 
'"thing1,blah","thing2,blah","thing3\\,blah",thing4 '

"thing1\blah","thing2\blah","thing3\,blah",thing4 
'"thing1\\blah","thing2\\blah","thing3\\,blah",thing4 '

答案 2 :(得分:0)

你可以试试这个正则表达式。


>>> re.sub('(?<!"),(?!")', r"\\,", 
                     '"thing1,blah","thing2,blah","thing3,blah",thing4')
#Gives "thing1\,blah","thing2\,blah","thing3\,blah",thing4

这背后的逻辑是用,代替\,,如果它不是立即前后跟"

答案 3 :(得分:0)

我想出了一个使用几个正则表达式函数的迭代解决方案:
finditer(),findall(),group(),start()和end()
有一种方法可以将所有这些变成一个自称的递归函数 任何接受者?

outfile  = open(outfileName,'w')

p = re.compile(r'["]([^"]*)["]')
q = re.compile(r'([^\\])(,)')
for line in outfileRl:
    pg = p.finditer(line)
    pglen = len(p.findall(line))

    if pglen > 0:
        mpgstart = 0;
        mpgend   = 0;

        for i,mpg in enumerate(pg):
            if i == 0:
                outfile.write(line[:mpg.start()])

            qg    = q.finditer(mpg.group(0))
            qglen = len(q.findall(mpg.group(0)))

            if i > 0 and i < pglen:
                outfile.write(line[mpgend:mpg.start()])

            if qglen > 0:
                for j,mqg in enumerate(qg):
                    if j == 0:
                        outfile.write( mpg.group(0)[:mqg.start()]    )

                    outfile.write( re.sub(r'([^\\])(,)',r'\1\\\2',mqg.group(0)) )

                    if j == (qglen-1):
                        outfile.write( mpg.group(0)[mqg.end():]      )
            else:
                outfile.write(mpg.group(0))

            if i == (pglen-1):
                outfile.write(line[mpg.end():])

            mpgstart = mpg.start()
            mpgend   = mpg.end()
    else:
        outfile.write(line)

outfile.close()

答案 4 :(得分:0)

你看过str.replace()吗?

  

str.replace(old,new [,count])       返回字符串的副本,其中包含所有出现的substring old   换成新的。如果给出了可选参数count,则只有   第一次计数的事件被替换。

here是一些文档

希望这会有所帮助

相关问题