繁体   English   中英

不能删除.text。 使用正则表达式

[英]cant remove .text. using a regular expression

说我有一个字符串:

"the quick brown fox jumped over the moon.this text needs to be removed."

我试图删除".this text needs to be removed." 使用Python。

我尝试了多种方法来做到这一点,主要由\\w+(\\..*\\.) ,但它不起作用。 我需要一种通用的方法来删除这个最后一部分,因为每个文件的文本都不同,所以像re.sub('\\.this text needs to be removed\\.', '', string)这样的东西对我来说不起作用。

你的正则表达式应如下所示:

re.sub(r'\.[^.]*?\.$', '', someString)

这将确保re.sub仅匹配字符串末尾的句点之间的文本。 如果没有$ ,它将匹配字符串中的任何匹配句点集。

编辑

如果你想捕获点之间的所有内容\\..*\\.

我同意abhijit,为什么不使用字符串函数? 例如:

s1="the quick brown fox jumped over the moon.this text needs to be removed."
s2=s1.replace(".this text needs to be removed.","")

虽然正则表达式非常强大,但字符串对象上的方法通常针对性能进行了优化。

阅读您的问题,您可以实现您想要的目标:

str = 'the quick brown fox jumped over the moon.this text needs to be removed.'
str = str.split('.this text needs to be removed.', 1)

print str[0] /* it prints "the quick brown fox jumped over the moon" */

你忘了逃避了. ,并犯了一些其他错误。 这应该工作:

s = "the quick brown fox jumped over the moon.this text needs to be removed."
s = re.sub("\..*\.", "", s)

如果你想用正则表达式做这个,只需使用sub。

>>> re.sub("\.this text needs to be removed\.","","the quick brown fox jumped over the moon.this text needs to be removed.")
'the quick brown fox jumped over the moon'

但是,使用Python字符串功能可以完成如此​​简单的任务

>>> "the quick brown fox jumped over the moon.this text needs to be removed.".replace(".this text needs to be removed.","")
'the quick brown fox jumped over the moon'

删除最后一句话的一般方法是

>>> re.sub("\.[^\.]+","","the quick brown fox jumped over the moon.this text needs to be removed.")
'the quick brown fox jumped over the moon.'

并且没有正则表达式

>>> ''.join("the quick brown fox jumped over the moon.this text needs to be removed.".rsplit('.',2)[:-2])
'the quick brown fox jumped over the moon'
>>> 

暂无
暂无

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

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