Regex replace text between delimiters in python

前端 未结 2 1340
無奈伤痛
無奈伤痛 2021-01-07 07:52

I need to fix some text that lies between delimiters for the following cases:
Case 1: {12345} (numbers between curlies) should become item_12345

相关标签:
2条回答
  • 2021-01-07 08:38

    This should get you started:

    s = '{123} and [456]'
    
    s = re.sub(r'\{(.+?)\}', r'foo_\1', s)
    s = re.sub(r'\[(.+?)\]', r'bar_\1', s)
    
    print s
    
    0 讨论(0)
  • 2021-01-07 08:40
    >>> import re
    >>> curly = re.compile('\{([0-9]+)\}')
    >>> square = re.compile('\[([0-9]+)\]')
    >>> s = "{242424} from X [100] bulks, linked to {57575757} from Y for [500]"
    >>> re.sub(square, lambda x: 'total_'+x.group(1), re.sub(curly, lambda x: 'item_
    '+x.group(1),s))
    'item_242424 from X total_100 bulks, linked to item_57575757 from Y for total_50
    0'
    
    0 讨论(0)
提交回复
热议问题