简体   繁体   English

使用正则表达式python通过匹配替换字符串

[英]Replace string by matching using regular expression python

Original String: 原始字串:

necessary information Leave a Comment unnecessary information

Required String: 必需的字符串:

necessary information

I have multiple strings that are in the above mentioned 'Original String' format. 我有多个上述“原始字符串”格式的字符串。 I want to remove the 'Leave a Comment' and 'unnecessary information'. 我要删除“留下评论”和“不必要的信息”。

Since 'Leave a Comment' is common in all string so I can build a Regular Expression on that? 由于“注释”在所有字符串中都很常见,因此我可以在其上构建正则表达式吗? And use that in 并在其中使用

string.replace( string , pattern )

The pattern here will be a Regular Expression. 这里的模式将是一个正则表达式。 How can I write a RE for this? 我如何为此写一个RE?

>>> s
'necessary information Leave a Comment unnecessary information'
>>> re.sub(r'\sLeave a Comment.*', '', s)
'necessary information'

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

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