簡體   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