Python regex - substitute until certain character

Viewed 65

I am looking to replace spaces with commas, but up to first / and tried the following:

import re

txt = "usera   28935 28876  0 Apr25 ?        00:07:20 /xxx/yyyy/foo/bar/zzzzz/Java/jdk-1.8.0_101/xxx/xxx -cp /xxx/yyyy/foo/bar/zzzzz"

rem = (re.sub(' +', ' ', txt))  # convert multiple spaces into single

print(re.sub(' ', ',', rem.lstrip()))

But the output is - inserts comma after every space!

usera,28935,28876,0,Apr25,?,00:07:20,/xxx/yyyy/foo/bar/zzzzz/Java/jdk-1.8.0_101/xxx/xxx,-cp,/xxx/yyyy/foo/bar/zzzzz

Expected Output:

usera,28935,28876,0,Apr25,?,00:07:20,/xxx/yyyy/foo/bar/zzzzz/Java/jdk-1.8.0_101/xxx/xxx -cp /xxx/yyyy/foo/bar/zzzzz

i.e. comma should be applied until the first /

I have tried lookahead, lookbehind but unable to work this out. Could someone advise me on how to achieve this please?

2 Answers

Whenever you have a problem like this, consider splitting before using a regex

# split the text once at the first /
a, b = txt.split("/", 1)

# do the replacement in the first half
a = re.sub(" +", ",", a)

# join 'em back up
result = "{}/{}".format(a,b)

You can use lookbehind, but it needs to be variable length. So, you'll need third-party regex module:

>>> import regex
>>> txt = "usera   28935 28876  0 Apr25 ?        00:07:20 /xxx/yyyy/foo/bar/zzzzz/Java/jdk-1.8.0_101/xxx/xxx -cp /xxx/yyyy/foo/bar/zzzzz"
>>> regex.sub(r'(?<!/.*) +', ',', txt)
'usera,28935,28876,0,Apr25,?,00:07:20,/xxx/yyyy/foo/bar/zzzzz/Java/jdk-1.8.0_101/xxx/xxx -cp /xxx/yyyy/foo/bar/zzzzz'

# or you can use \G
>>> regex.sub(r'\G([^/ ]*+) +', r'\1,', txt)
'usera,28935,28876,0,Apr25,?,00:07:20,/xxx/yyyy/foo/bar/zzzzz/Java/jdk-1.8.0_101/xxx/xxx -cp /xxx/yyyy/foo/bar/zzzzz'

The first one replaces spaces only if / character is not present earlier in the string.

The second one defines a sequence of other than space or / characters followed by spaces to be matched as many times as possible from the start of the string.

Related