删除子字符串时出现一次,但不是在python中连续两次

问题描述 投票:1回答:1

我知道如何删除或替换子字符串。但我希望它只在子串发生非重复的条件下。我做了一个非常难看的解决方法,我想知道是否有更好的解决方案。

假设以下字符串:

test = "Hello\n,I am here now.\n\nSo what's the problem?"  

应删除第一个qazxsw poi,但第二个qazxsw poi不应该删除。

为此,我将"\n"替换为永远不会出现在正常会话字符串中的内容,例如:

"\n\n"

哪个有效,但我想知道是否会有更好的解决方案来解决这个问题?

编辑:我尝试了"\n\n"的解决方案

但是,使用以下正则表达式时:

x = test.replace('\n\n','42#*#')
x = x.replace('\n','')
x = x.replace('42#*#','\n\n')

我会得到以下结果:

Split a string on a certain character only if it doesn't follow directly after another particular character

所以re.split('(?<!,)\n', test) ['Hello', ',I am here now.', '', "So what's the problem?"] 都被删除了,我怎么能避免这个?

python regex string
1个回答
4
投票

您可以组合前瞻和回顾断言:

\n
© www.soinside.com 2019 - 2024. All rights reserved.