pythonregex

How to replace a period that is between letters, but not numbers?


I need to change a string that looks like this: chad.floor = 3.5 to: chad_floor = 3.5

Only the . that is between letters is replaced, not the one with numbers.

I've looked and researched and I keep coming up with this, which does not work:

("[\w*].[\w*]", "_", "chad.floor = 3.45")

This results in: ___r = _5

Which, from what I can tell, is just replacing everything in the match.

How can I modify my RE to keep all the text, and only replace the . that is between letters but not numbers?


Solution

  • Try:

    (?<=[a-zA-Z])\.(?=[a-zA-Z])
    

    and replacing with:

    _
    

    See: regex101


    Explanation

    Replace

    Comment on your attempt:

    [\w*] does not at all do what I guess you think it does:

    1. \w matches roughly [0-9a-zA-Z_] and not only letters.
    2. [ X* ] does not mean any number of "X" but rather adds the literal asterix to the character class.
    3. [\w] is the same as \w.
    4. "Even" [a-zA-Z]*\.[a-zA-Z]* would also match the dot in "1.2" since the asterix could match 0 occurences of letters.
    5. By matching the letters to the right and left they get replaced too.