Regex replace (in Python) - a simpler way?

前端 未结 4 476
广开言路
广开言路 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:34

    >>> import re
    >>> s = "start foo end"
    >>> s = re.sub("foo", "replaced", s)
    >>> s
    'start replaced end'
    >>> s = re.sub("(?<= )(.+)(?= )", lambda m: "can use a callable for the %s text too" % m.group(1), s)
    >>> s
    'start can use a callable for the replaced text too end'
    >>> help(re.sub)
    Help on function sub in module re:
    
    sub(pattern, repl, string, count=0)
        Return the string obtained by replacing the leftmost
        non-overlapping occurrences of the pattern in string by the
        replacement repl.  repl can be either a string or a callable;
        if a callable, it's passed the match object and must return
        a replacement string to be used.
    

提交回复
热议问题