簡體   English   中英

如何使用REGEX從字符串中替換分號的確切數字?

[英]How to substitute exact number of semi-colon from string using REGEX?

我需要刪除所有出現的單個分號,但要保留兩次出現的內容。

輸入:

poop,hello\/# what;up,\wor;;ld; yolo| s|ag"j"d\nhdhf,\;;

預期產量:

poop hello    what up  wor;;ld  yolo| s|ag"j"d hdhf  ;;

因此,我能夠刪除除單個分號以外的所有內容。

a=re.sub(r'[^\w|\d|(;;)|\|"]'," ",a)

其中a是顯示在頂部的字符串。

但這給了我:

poop hello    what;up  wor;;ld; yolo| s|ag"j"d hdhf  ;;

怎么了

嘗試:

s.replace(";;","$").replace(";"," ").replace("$",";;")

替換;; $ ,比取代; 成比更換背面空間;;

您可以使用負向前瞻和負向后瞻:

>>> re.sub(r'[^\w\d;|"]|(?<!;);(?!;)'," ",a)
'poop hello   what up  wor;;ld  yolo| s|ag"j"d nhdhf  ;;'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM