如何使用REGEX替换字符串中分号的确切数目?

2024-10-02 14:27:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要删除所有出现的单个分号,但保留两个出现的分号。你知道吗

输入:

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  ;;

这里怎么了?你知道吗


Tags: 字符串re内容helloyolowhat产量up
2条回答

尝试:

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

;;替换为$,而将;替换为空格,而不是替换回;;。你知道吗

您可以使用负向前看和负向后看:

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

相关问题 更多 >