Search code examples
pythonregexpython-re

Splitting words before and after '/' in using Regex


Have the following string:

text = 'interesting/practical/useful'

I need to split it like interesting / practical / useful using Regex.

I'm trying this

newText = re.sub(r'[a-zA-Z](/)[a-zA-Z]', ' \g<0> ', text)

but it returns

interestin g/p ractica l/u seful

P.S. I have other texts in the Corpus that also have forward slashes that shouldn't be altered due to this operation, which is my I'm looking for regex patterns specifically with characters before and after the '/'.


Solution

  • Use lookarounds for the letters before and after the /, so they're not included in the match.

    newText = re.sub(r'(?<=[a-zA-Z])/(?=[a-zA-Z])', ' \g<0> ', text)