Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
918 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 Reply

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?"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...