2016-08-03 182 views
1

我需要一個給我~^在python中提取2個字符串之間的字符串?

之間的字符串我有串這樣

:::ABC???,:::DEF???

我需要使用python

我想做的事情,讓他們之間的字符串所有這一切,因爲我試圖從HTML頁面提取文本。像這個例子一樣

<td class="cell-1"> 
    <div><span class="value-frame">&nbsp;~ABC^,~DEF^</span></div> 
</td> 

回答

1

好像你想ABC和DEF,所以你需要編寫再像這樣(。*?)

import re 
target = ' <td class="cell-1"><div><span class="value-frame">&nbsp;~ABC^,~DEF^</span></div></td>' 
matchObj = re.findall(r'~(.*?)\^', target) 
print matchObj 
# ['ABC', 'DEF'] 

您可以瞭解更多關於重新模塊

+0

是什麼意思'(*。 ?)'? – dragon

1

您可以在生成器表達式中使用isalpha()函數。然後使用join()將字符組合爲單個string

def extract_string(s): 
    return ''.join(i for i in s if i.isalpha()) 

輸出示例:

print extract_string(':::ABC???,:::DEF???') 
>>> ABCDEF 

但是,如果你想~...^之間只提取字符僅用於提取所有字符,:

import re 
def extract_string(s): 
    match = re.findall(r"~([a-zA-z]*)\^", s) 
    return match 

輸出示例:

s = '&nbsp;~ABC^,~DEF^' 
print extract_string(s) 
>>> ['ABC', 'DEF'] 

只是一個側面說明:如果你使用解析正則表達式 /或字符串操作HTML,爲famous S.O. reply建議,請使用HTML解析器;如Beautiful Soup庫改爲:D!

相關問題