pythonregexsearchreplacetext-search

Search And Replace With Regex with header and tail


I'm new to regex and I want to search and replace every occurrence of a "variable".mean() with average("variable")

m863991.mean() to average(m463641) or

m863992.mean() to average(m463642)

Where the beginning of the variable starts with m and ends with 1 or 2 with 5 digits in between.


Solution

  • You can use re.sub passing lambda for the replacement text. You can use the pattern (.*?)\.mean\(\), and surround the captured group with parenthesis, and starting it with average

    >>> import re
    >>> text='m863991.mean()'
    >>> re.sub('(.*?)\.mean\(\)', lambda  x: 'average('+x.group(1)+')', text)
    'average(m863991)'
    

    But to be specific, as you have mentioned the criteria for these values, you can use the pattern (m\d{5}[12])\.mean\(\) for the values that start with m, 5 digits in the middle, and ending with 1 or 2, and .mean() at last.

    >>> re.sub('(m\d{5}[12])\.mean\(\)', lambda  x: 'average('+x.group(1)+')', text)
    'average(m863991)'