1

I have a text like this :

text = "hey , i am new here . number is 8,5%"

And i want my output to be like this :

hey, i am new here. number is 8,5%

So am using this regex code :

text= re.sub(r'\s*([.,?:])\s*', r'\1 ',text) 

The output of this code is :

hey, i am new here. number is , 5%

I don't want the numbers to be touched with my regex code.

Am using Python3

2 Answers 2

2

You can use (?<!\d)\s*([.,?:])\s*.
(?<!\d) means "If not preceded by a digit"

Full piece of code: text= re.sub(r'\s*([.,?:])\s*', r'\1 ',text)

Sign up to request clarification or add additional context in comments.

Comments

1

You can use

re.sub(r'\s*([?:]|(?<!\d)[.,](?!\d))\s*', r'\1 ',text)

See the Python demo and the regex demo.

Details:

  • \s* - zero or more whitespaces
  • ([?:]|(?<!\d)[.,](?!\d)) - Group 1:
    • [?:] - a ? or :
    • | - or
    • (?<!\d)[.,](?!\d) - a . or , not preceded nor followed with a digit
  • \s* - zero or more whitespaces.

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.