As part of preprocessing my data. I want to be able to replace space followed by a number, keeping the space followed by a character. For example:
Input String: '8.1.7 Sep 2000 Dec 2004 Dec 2006 Indefinite'
Expected output: '8.1.7,Sep 2000,Dec 2004,Dec 2006,Indefinite'
I am using the regular expression based replace function in python:
re.sub("\s+", ",", release)
but this is not fetching the desired result, simply because this meant to replace all spaces, not sure how to keep the one followed by characters i.e. [a-z]
.
Or maybe I need to rethink on approach.
You may use a (?<=\d)
to require a digit before the whitespace:
release = re.sub(r"(?<=\d)\s+", ",", release)
See the regex demo
Details
(?<=\d)
- a positive lookbehind that requires a digit to appear immediately to the left of the current location\s+
- 1 or more whitespace chars.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With