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