user19416874
user19416874

Reputation: 1

python re sub using regex

I have a requirement to match and replace the continuous spaces that has from 3-20 spaces to just 3 spaces. However, I want to retain the leading spaces as it is. I tried using the negative lookbehind but it is not working as expected.

>>> import re
>>> a="          command1 command2         abc      def       command3     ghi"
>>> re.sub("(?!^)\s{3,20}", "   ", a)
'    command1 command2   abc   def   command3   ghi'
>>> re.sub("(?<!^)\s{3,20}", "   ", a)
'    command1 command2   abc   def   command3   ghi'

Just to re-iterate my requirement, I want to do below changes,

a="          command1 command2         abc      def       command3     ghi"

to

a="          command1 command2   abc   def   command3   ghi"

my python ver is 2.7. Can anyone please help?

Upvotes: 0

Views: 57

Answers (2)

Rabinzel
Rabinzel

Reputation: 7903

You could start checking whitespaces after the first time there is a word.

Check Regex101.

import re
a="          command1 command2         abc      def       command3     ghi"
pat = r"(?<=\w)(\s{3,20})"
re.sub(pat, "   ", a)

'          command1 command2   abc   def   command3   ghi'

Upvotes: 1

Tim Roberts
Tim Roberts

Reputation: 54698

Count the leading spaces and handle them separately.

import re
a="          command1 command2         abc      def       command3     ghi"
lead = len(a)-len(a.lstrip())
a = a[:lead] + re.sub("\s{3,20}", "   ", a[lead:])
print(a)

Upvotes: 0

Related Questions