How to replace an re match with a transformation of that match?

前端 未结 2 480
长情又很酷
长情又很酷 2021-01-13 09:02

For example, I have a string:

The struct-of-application and struct-of-world

With re.sub

相关标签:
2条回答
  • 2021-01-13 09:51

    Try this:

    >>> p = re.compile(r"((\w+-)+\w+)")
    >>> p.sub('[\\1](http://\\1)','The struct-of-application and struct-of-world')
    'The [struct-of-application](http://struct-of-application) and [struct-of-world](http://struct-of-world)'
    
    0 讨论(0)
  • 2021-01-13 09:54

    Use a function for the replacement

    s = 'The struct-of-application and struct-of-world'
    p = re.compile('((\w+-)+\w+)')
    def replace(match):
        return 'http://{}'.format(match.group())
        #for python 3.6+ ... 
        #return f'http://{match.group()}'
    
    >>> p.sub(replace, s)
    
    'The http://struct-of-application and http://struct-of-world'
    >>>
    
    0 讨论(0)
提交回复
热议问题