繁体   English   中英

在python中使用正则表达式删除特定字符之间的空格

[英]remove white space between specific characters using regex in python

我正在尝试使用正则表达式按连续的'?'顺序删除空格。 和/或“!” 在一个字符串中。 一个例子是“那是什么?????????! 应该更改为“那是什么?????????? !!!?!”。 也就是说,我想将所有的'?'连接在一起 和'!' 中间没有空格。 我当前的代码效果不佳:

import re
s = "what is that ?? ? ? ?? ??? ? ! ! ! ? !"
s = re.sub("\? +\?", "??", s)
s = re.sub("\? +\!", "?!", s)
s = re.sub("\! +\!", "!!", s)
s = re.sub("\! +\?", "!?", s)

产生“那是什么??? ???????! !?!',其中显然没有删除一些空格。 我的代码出了什么问题以及如何修改它?

您只是想压缩标点符号周围的空格,是吗? 这样的事情怎么样:

>>> import re
>>> s = "what is that ?? ? ? ?? ??? ? ! ! ! ? !"
>>> 
>>> re.sub('\s*([!?])\s*', r'\1', s)
'what is that??????????!!!?!'

如果您真的对为什么您的方法不起作用感兴趣,则与正则表达式在字符串中的移动方式有关。 当您编写re.sub("\\? +\\?", "??", s)并在您的字符串上运行它时,引擎将像这样工作:

s = "what is that ?? ? ? ?? ??? ? ! ! ! ? !"
# first match -----^^^
# internally, we have:
s = "what is that ??? ? ?? ??? ? ! ! ! ? !"
# restart scan here -^
# next match here ----^^^
# internally:
s = "what is that ??? ??? ??? ? ! ! ! ? !"
# restart scan here ---^
# next match here ------^^^

等等。 有几种方法可以防止光标在检查匹配项时前进(检查正向提前)。

如果您想像@gddc所说的那样并且句子模式是相同的,那么您可以尝试以下方法:

string_="what is that ?? ? ? ?? ??? ? ! ! ! ? !"
string_1=[]
symbols=[]
string_1.append(string_[:string_.index('?')])
symbols.append(string_[string_.index('?'):])
string_1.append("".join(symbols[0].split()))
print("".join(string_1))

输出:

what is that ??????????!!!?!

我的方法包括将字符串分成两部分,然后使用正则表达式处理问题区域(删除空格),然后将片段重新结合在一起。

import re s = "what is that ?? ? ? ?? ??? ? ! ! ! ? !" splitted = s.split('that ') # don't forget to add back in 'that' later splitfirst = splitted[0] s = re.sub("\\s+", "", splitted[1]) finalstring = splitfirst+'that '+s print(finalstring) import re s = "what is that ?? ? ? ?? ??? ? ! ! ! ? !" splitted = s.split('that ') # don't forget to add back in 'that' later splitfirst = splitted[0] s = re.sub("\\s+", "", splitted[1]) finalstring = splitfirst+'that '+s print(finalstring)输出:

╭─jc@jc15 ~/.projects/tests ╰─$ python3 string-replace-question-marks.py what is that ??????????!!!?!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM