Reputation: 663
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
Upvotes: 1
Views: 223
Reputation: 21
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)
Upvotes: 2
Reputation: 626738
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.Upvotes: 1