使用regex删除格式字符串

2024-09-24 22:30:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串格式:

(header1:content1(note1, note2),content2(note3),content3)-(header2:content)-(header3)

现在我想删除所有内容,我想要的输出是

(header1)-(header2)-(header3)

我该怎么做?我尝试了一些正则表达式,但输出不正确。你知道吗

更新1:headercontentnote可以包含除()之外的任何字符。你知道吗

更新2: @阿德史密斯解决了我原来的问题。现在我的字符串格式如下:

normalcontent1-(header1:content1(note1, note2),content2(note3),content3)-(header2:content)-normalcontent2-(header3)

预期产量:

normalcontent1-(header1)-(header2)-normalcontent2-(header3)

Tags: 字符串内容格式contentheader1header2header3note1
2条回答
def getheaders(text):
    elements = re.split("(?<=\))-",text)
    return '-'.join(["("+header.split(":")[0].strip("()")+")" for header in elements])

text = "(header1:content1(note1, note2),content2(note3),content3)-(header2:content)-(header3)"
getheaders(text)
>>> '(header1)-(header2)-(header3)'

请注意,如果header包含:,则此操作将失败,因此如果这些情况看起来不正确,您可能需要手动解析它们。我没有一个很好的解决方案,如果我不能从内容中划出标题,对不起。如果内容不能有:,你可以只做split(":")[:-2],但是如果头和内容都可以包含一个:,那么就不可能(以编程的方式)知道头的结束和内容的开始。你知道吗

以下是pyparsing的示例:

import pyparsing as pp
import re

txt='''normalcontent1-(header1:content1(note1, note2),content2(note3),content3)-(header2:content)-normalcontent2-(header3)
normalcontent1-(header:content)-normalcontent2-normalcontent3-(header2:content2‌​)'''

def DashSplit(txt):
    ''' Replicate the function of str.split(',') but do not split on nested expressions or in quoted strings'''
    com_lok=[]
    dash = pp.Suppress('-')
    # note the location of each dash outside an ignored expression:
    dash.setParseAction(lambda s, lok, toks: com_lok.append(lok))
    ident = pp.Word(pp.alphas+"_", pp.alphanums+"_")  # python, C type identifier
    exp=(pp.nestedExpr())                             # Ignore everthing inside nested '( )'

    atom = ident | exp 
    expr = pp.OneOrMore(atom) + pp.ZeroOrMore(dash  + atom )
    try:
        result=expr.parseString(txt)
    except pp.ParseException as e:
        print('nope', e)
        return [txt]
    else:    
        return [txt[st:end] for st,end in zip([0]+[e+1 for e in com_lok],com_lok+[len(txt)])]      

def headerGetter(txt):
    m=re.match(r'\((\w+)', txt)
    if m:
        return '('+re.match(r'\((\w+)', txt).group(1)+')' 
    else:
        return txt    

for line in txt.splitlines():    
    print('-'.join(headerGetter(e) for e in DashSplit(line))) 

印刷品:

normalcontent1-(header1)-(header2)-normalcontent2-(header3)
normalcontent1-(header)-normalcontent2-normalcontent3-(header2)

如果正确定义语法,解析器将是比正则表达式更健壮的解决方案。你知道吗

相关问题 更多 >