How to input a regex in string.replace?

前端 未结 7 1817
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 06:50

I need some help on declaring a regex. My inputs are like the following:

this is a paragraph with<[1> in between and then there are cases ..         


        
相关标签:
7条回答
  • 2020-11-22 07:22

    I would go like this (regex explained in comments):

    import re
    
    # If you need to use the regex more than once it is suggested to compile it.
    pattern = re.compile(r"</{0,}\[\d+>")
    
    # <\/{0,}\[\d+>
    # 
    # Match the character “<” literally «<»
    # Match the character “/” literally «\/{0,}»
    #    Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «{0,}»
    # Match the character “[” literally «\[»
    # Match a single digit 0..9 «\d+»
    #    Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
    # Match the character “>” literally «>»
    
    subject = """this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>. 
    and there are many other lines in the txt files
    with<[3> such tags </[3>"""
    
    result = pattern.sub("", subject)
    
    print(result)
    

    If you want to learn more about regex I recomend to read Regular Expressions Cookbook by Jan Goyvaerts and Steven Levithan.

    0 讨论(0)
提交回复
热议问题