How to match a specific character only if it is followed by string containing specific characters

Viewed 107

I'm trying to replace slashes in a string, but not all of them - only the ones before first comma. To do that, I probably have to find a way to match only slashes being followed by string containing a comma.

Is it possible to do this using one regexp, i.e. without first splitting the string by commas?

Example input string:

Abc1/Def2/Ghi3,/Dore1/Mifa2/Solla3,Sido4

What I want to get:

Abc1.Def2.Ghi3,/Dore1/Mifa2/Solla3,Sido4

I've tried some lookahead and lookbehind techniques with no effect, so currently to do this in e.g. Python I first split the data:

test = 'Abc1/Def2/Ghi3,/Dore1/Mifa2/Solla3,Sido4'
strlist = re.split(r',', test)
result = ','.join([re.sub(r'\/', r'.', strlist[0])] + strlist[1:])

What I would prefer is to use a specific regexp pattern instead of Python-oriented solution though, so essentially I could have a pattern and replacement such that the following code would give me the same result:

result = re.sub(pattern, replacement, test)

Thanks for all regex-avoiding answers - I was wondering if I could do this using only regex (so e.g. I could use sed instead of Python).

2 Answers
Related