Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
916 views
in Technique[技术] by (71.8m points)

regex - How to strip whitespace from before but not after punctuation in python

relative python newbie here. I have a text string output from a program I can't modify. For discussion lets say:

text = "This text . Is to test . How it works ! Will it! Or won't it ? Hmm ?"

I want to remove the space before the punctuation, but not remove the second space. I've been trying to do it with regex, and I know that I can match the instances I want using match='s[?.!"]s' as my search term.

x=re.search('s[?.!"]s',text)

Is there a way with a re.sub to replace the search term with the leading whitespace removed? Any ideas on how to proceed?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Put a group around the text you want to keep and refer to that group by number in the replacement pattern:

re.sub(r's([?.!"](?:s|$))', r'1', text)

Note that I used a r'' raw string to avoid having to use too many backslashes; you didn't need to add quite so many, however.

I also adjusted the match for the following space; it now matches either a space or the end of the string.

Demo:

>>> import re
>>> text = "This text . Is to test . How it works ! Will it! Or won't it ? Hmm ?"
>>> re.sub(r's([?.!"](?:s|$))', r'1', text)
"This text. Is to test. How it works! Will it! Or won't it? Hmm?"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...