2
s = '^^^@ """@$ raw data &*823ohcneuj^^^ Important Information ^^^raw data^^^ Imp Info'
其中,我想删除分隔符^^^和^^^之间的文本。删除两个正则表达式之间的特殊字符分隔符
输出应该是“重要信息进出口信息”
s = '^^^@ """@$ raw data &*823ohcneuj^^^ Important Information ^^^raw data^^^ Imp Info'
其中,我想删除分隔符^^^和^^^之间的文本。删除两个正则表达式之间的特殊字符分隔符
输出应该是“重要信息进出口信息”
你可以用正则表达式做到这一点:
import re
s = '^^^@ """@$ raw data &*823ohcneuj^^^ Important Information ^^^raw data^^^ Imp Info'
important = re.compile(r'\^\^\^.*?\^\^\^').sub('', s)
在这个正则表达式的关键要素是:
^
特点,因为它有特殊的含义.*?
def removeText(text):
carrotCount = 0
newText = ""
for char in text:
if(char == '^'):
# Reset if we have exceeded 2 sets of carrots
if(carrotCount == 6):
carrotCount = 1
else:
carrotCount += 1
# Check if we have reached the first '^^^'
elif(carrotCount == 3):
# Ignore everything between the carrots
if(char != '^'):
continue;
# Add the second set of carrots when we find them
else:
carrotCount += 1
# Check if we have reached the end of the second ^^^
# If we have, we have the message
elif(carrotCount == 6):
newText += char
return newText
这将打印 “重要信息进出口信息。”
谢谢,我试过同样的方式,但没有应用“\”,所以没有得到输出。 – user7276674