How to Insert spaces in the whole string among characters except ANYTHING which looks like \something, using Regex

Viewed 46

I have a string like s = '{qcos\\theta_{g}\\over r})^{2\\over 1 + \\alpha^{2}}}\\ 1234'

and if I use the regex (?<=.)(?!$) as I have used in this example, it gives me the whole string split in white characters. But I want to preserve anything \wordonly so for example in the above given string, I want the answer to be

'{ q c o s \\theta _ { g } \\over r } ) ^ { 2 \\over 1 + \\alpha ^ { 2 } } } \\ 1 2 3 4'

where \theta remains the same but 123 becomes 1 2 3, abc becomes a b c and \theta_{21} becomes \theta _ { 2 1 }

1 Answers

You can use

import re
s = '{qcos\\theta_{g}\\over r})^{2\\over 1 + \\alpha^{2}}}\\ 1234'
print( ' '.join(re.findall(r'\\[a-zA-Z]*|\S', s)) )
# => { q c o s \theta _ { g } \over r } ) ^ { 2 \over 1 + \alpha ^ { 2 } } } \ 1 2 3 4

See the Python demo.

With re.findall(r'\\[a-zA-Z]*|\S', s), you get a list of \+letters and any single non-whitespace chars.

Then, all you need is to join the found items with a space, ' '.join(...).

Regex details:

  • \\ - a \ char
  • [a-zA-Z]* - zero or more ASCII letters
  • | - or
  • \S - any non-whitespace char.

See the regex demo.

Related