[Python] How to match a substring using a pattern and replace by passing a variable in RegEx,...

Discussão em 'Python' iniciado por Stack, Abril 29, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to iterate through a Pandas dataframe's column values one by one to detect a substring with a RegEx pattern and replace it wherever it shows up. The string values in the dataframe's target column have the following variations:

    1. 'func(something)...'
    2. 'func(something,something)...'

    I am attempting to target the values with the 2nd variation and replace the comma-separated substring by a value from another column in the same row.

    My code looks like:

    import re
    for i, x in enumerate(df['col1']):
    df.loc[i,'col2'] = re.sub(r'^(func\().+,.+(\).*)', r'\1%s\2'%(x), df.loc[i,'col2'])


    I have had a successful output on a terminal when I replace the * in the pattern with +:

    [​IMG]

    This doesn't quite feel right since the .* should accommodate for 0 or more instances of any character after the final captured parenthesis \).

    However, at least it works because when I try to replicate it on VSCode with Python on the dataframe's column values, it does not make any changes.

    Am I missing anything?

    Continue reading...

Compartilhe esta Página