0

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?

2 Answers 2

1

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'
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.