Regex replace (in Python) - a simpler way?

前端 未结 4 478
广开言路
广开言路 2020-12-12 22:16

Any time I want to replace a piece of text that is part of a larger piece of text, I always have to do something like:

\"(?Psome_pattern)(?P<         


        
4条回答
  •  不知归路
    2020-12-12 22:41

    I believe that the best idea is just to capture in a group whatever you want to replace, and then replace it by using the start and end properties of the captured group.

    regards

    Adrián

    #the pattern will contain the expression we want to replace as the first group
    pat = "word1\s(.*)\sword2"   
    test = "word1 will never be a word2"
    repl = "replace"
    
    import re
    m = re.search(pat,test)
    
    if m and m.groups() > 0:
        line = test[:m.start(1)] + repl + test[m.end(1):]
        print line
    else:
        print "the pattern didn't capture any text"
    

    This will print: 'word1 will never be a word2'

    The group to be replaced could be located in any position of the string.

提交回复
热议问题