Search code examples
pythonregexreplaceappendcarriage-return

Appending to a line


I have a certain string fruits as such:

Apples
Bananas
Pineapples

There is a carriage return \r at the end of each line, as well as at the beginning and end of the string. Using RegEx, how would I go about appending : 1 to the end of the first line Apples? I have tried the following to no avail:

re.sub("Apples(\r)", "\1:1", fruits)

My thinking was that \1 should replace what's in the brackets (\r), however everything in the pattern is being replaced.


Solution

  • What you are doing is matching "Apples\r", capturing the "\r" in the process, and then replacing the entire match with "\r:1".

    For this simple example, there's no need to capture matches to \r, anyway, since the only thing that will match it is \r. You can hard code that into the replacement string.

    I'll assume you want the resulting string to be "\rApples: 1\rBananas\rPineapples\r.

    You can use a lookbehind so that Apples is not consumed (though I hear that consuming one a day keeps the doctor away):

    re.sub("(?<=Apples)\r", ": 1\r", fruits)
    

    But you could also just do:

    re.sub("Apples\r", "Apples: 1\r", fruits)
    

    The lookbehind would be more useful if you wanted to add : 1 after each fruit:

    re.sub("(?<=[^\r])\r", ": 1\r", fruits)
    

    The above says find every \r that follows a character that isn't an \r, and replace them with : 1\r. The result would then be:

    # \rApples: 1\rBananas: 1\rPineapples: 1\r\r