3 回答

TA贡献1862条经验 获得超6个赞
您应该使用re.split并在后面进行负向查找来检查反斜杠字符。
import re
pattern = r'(?<!\\):'
s = 'I:would:like:to:find\:out:how:this\:works'
print(re.split(pattern, s))
输出:
['I', 'would', 'like', 'to', 'find\\:out', 'how', 'this\\:works']

TA贡献1835条经验 获得超7个赞
您可以将“:\”替换为某些内容(只需确保此内容在其他位置的字符串中不存在...您可以使用长期项或其他内容),然后用“:”分隔放回原处。
[x.replace("$","\:") for x in str1.replace("\:","$").split(":")]
解释:
str1 = 'I:would:like:to:find\:out:how:this\:works'
将“:”替换为“ $”(或其他):
str1.replace("\:","$")
Out: 'I:would:like:to:find$out:how:this$works'
现在以“:”分隔
str1.replace("\:","$").split(":")
Out: ['I', 'would', 'like', 'to', 'find$out', 'how', 'this$works']
并为每个元素将“ $”替换为“:”:
[x.replace("$","\:") for x in str1.replace("\:","$").split(":")]
Out: ['I', 'would', 'like', 'to', 'find\\:out', 'how', 'this\\:works']

TA贡献1785条经验 获得超4个赞
用 re.split
前任:
import re
s = "I:would:like:to:find\:out:how:this\:works"
print( re.split(r"(?<=\w):", s) )
输出:
['I', 'would', 'like', 'to', 'find\\:out', 'how', 'this\\:works']
添加回答
举报