Search code examples
python-3.xregexsubstring

Replace matched susbtring using re sub


Is there a way to replace the matched pattern substring using a single re.sub() line?. What I would like to avoid is using a string replace method to the current re.sub() output.

Input =  "/J&L/LK/Tac1_1/shareloc.pdf"

Current output using re.sub("[^0-9_]", "", input): "1_1"

Desired output in a single re.sub use: "1.1"

Solution

  • According to the documentation, re.sub is defined as

    re.sub(pattern, repl, string, count=0, flags=0)
    

    If repl is a function, it is called for every non-overlapping occurrence of pattern.

    This said, if you pass a lambda function, you can remain the code in one line. Furthermore, remember that the matched characters can be accessed easier to an individual group by: x[0].

    I removed _ from the regex to reach the desired output.

    txt = "/J&L/LK/Tac1_1/shareloc.pdf"
    x = re.sub("[^0-9]", lambda x: '.' if x[0] is '_' else '', txt)
    print(x)