简体   繁体   English

如何使用python regex从字符串中删除指定的模式?

[英]How to remove a specified pattern from the string with python regex?

Here is my string '2018-01-31 05:29:37 | Jan Pong Lee | [Number of contacts]:1' 这是我的字符串'2018-01-31 05:29:37 | Jan Pong Lee | [Number of contacts]:1' '2018-01-31 05:29:37 | Jan Pong Lee | [Number of contacts]:1'

I would like to remove '| Jan Pong Lee |' 我想删除'| Jan Pong Lee |' '| Jan Pong Lee |' . The name can have 2 or 4 words, is there a way to do that? 这个名字可以有2个或4个单词,有没有办法做到这一点?

You can use this regex to match and replace it with empty string, 您可以使用此正则表达式匹配并将其替换为空字符串,

\|[^|]*\|

Explanation of this regex: This regex basically captures a | 这个正则表达式的解释:这个正则表达式基本上捕获了一个| followed by any character (except | ) zero or more times and finally captures a | 后跟任何字符(除了| )零次或多次,最后捕获一个| character and then stops capturing and replaces all matched characters with empty string. 字符然后停止捕获并用空字符串替换所有匹配的字符。

Live Demo 现场演示

Here is the python code for same, 这是相同的python代码,

import re

s = '2018-01-31 05:29:37 | Jan Pong Lee | [Number of contacts]:1'
ret = re.sub(r'\|[^|]*\|', '', s)
print (ret)

Which prints the remaining string after removal of | Jan Pong Lee | 在删除| Jan Pong Lee |之后打印剩余的字符串 | Jan Pong Lee | . This will work no matter whatever number of words you have inside those pipes. 无论你在这些管道里面有多少单词,这都可以工作。

2018-01-31 05:29:37  [Number of contacts]:1

Here is solution: 这是解决方案:

old_str =  '2018-01-31 05:29:37 | Jan Pong Lee | [Number of contacts]:1'
new_str = "{} | {}".format(old_str.split('|')[0], old_str.split('|')[2])

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

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