繁体   English   中英

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

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

这是我的字符串'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'

我想删除'| Jan Pong Lee |' '| Jan Pong Lee |' 这个名字可以有2个或4个单词,有没有办法做到这一点?

您可以使用此正则表达式匹配并将其替换为空字符串,

\|[^|]*\|

这个正则表达式的解释:这个正则表达式基本上捕获了一个| 后跟任何字符(除了| )零次或多次,最后捕获一个| 字符然后停止捕获并用空字符串替换所有匹配的字符。

现场演示

这是相同的python代码,

import re

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

在删除| Jan Pong Lee |之后打印剩余的字符串 | Jan Pong Lee | 无论你在这些管道里面有多少单词,这都可以工作。

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

这是解决方案:

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