2016-06-14 36 views
-1

我有一個這樣的字符串:如何使Python中的子字符串,但爲我的例子?

<node> user = "bob" password ="123" </node> <node> user = "john" password ="123" </node> <node> user = "will" password ="1234" </node> <node> user = "andrew" password ="12345" </node> <node> user = "mike" password ="123456" </node> 

我怎麼能只提取用戶?我想得到一個名單有鮑勃,約翰,將,安德魯,邁克和其他所有這種格式:user = "XXXX"

我檢查了一些子字符串的方法,但沒有解決我的問題。您可以使用切片方法設置開始和結束索引,但我不想使用整數,我想按字符串搜索。

+2

*「你能請任何代碼來解決我的問題嗎?」* - 這是**不** **如何堆棧溢出的作品。 *寫一些自己*,並學習[問]。 *「如何做......但對我的例子」*是整個學習**的全部觀點,如果你不能採用一般的解決方案來滿足你的具體需求,那麼你就被塞滿了(而SO是毫無意義的)。 – jonrsharpe

+0

你的回答毫無意義。我只是用「解決我的問題」,因爲我沒有得到我已經嘗試過的答案(我總是先Google)。我的問題比這個問題要大得多。但我認爲它非常客觀和簡單,這樣人們可以花更少的時間閱讀,我花更少的時間等待,然後我得到一個可用的代碼,並使用提供的代碼爲我的問題提出解決方案。這是學習的重點。快速和簡單。 –

+0

這不是一個答案,它是一個評論。我很欣賞把這個問題歸結爲核心問題的努力,但是SO在這裏不是**,所以你「花費更少的時間等待,然後......獲得一個可行的代碼」。請參加[旅遊]。 – jonrsharpe

回答

1

這可以用一個簡單的正則表達式來完成:

>>> s = '<node> user = "bob" password ="123" </node> <node> user = "john" password ="123" </node> <node> user = "will" password ="1234" </node> <node> user = "andrew" password ="12345" </node> <node> user = "mike" password ="123456" </node>' 
>>> import re 
>>> re.findall(r'user = "(\w+)"', s) 
['bob', 'john', 'will', 'andrew', 'mike'] 

如果您需要支持對他們有空格的名稱,正則表達式稍有變化。從\w+捕獲組(所有字母數字字符)更改爲[^"]+(一切,這是不是一個雙引號):

>>> s = '<node> user = "bob jones" password ="123" </node> <node> user = "john" password ="123" </node> <node> user = "will" password ="1234" </node> <node> user = "andrew" password ="12345" </node> <node> user = "mike" password ="123456" </node>' 
>>> re.findall(r'user = "([^"]+)"', s) 
['bob jones', 'john', 'will', 'andrew', 'mike'] 

我敢肯定,有更好的方法(也許解析出第一個node標籤與一個xml解析器和然後解析節點中的「user = ...」),但這應該至少指向正確的方向或幫助塑造你對問題的思考。

+0

謝謝。我無法測試它,但它非常有幫助。我會爲此工作。 –

+0

這樣的工作,但我仍然在想如何提取其中的空格名稱:例如:鮑勃約翰遜..它只得到鮑勃 –

+0

@AndréRamos - 我認爲'r'user =「([^」] +)''會爲此工作。 – mgilson

0

這是瞭解Python字符串和列表的好方法。既然你最初有一個字符串,字符串有一個劃分方法,可以讓你基於傳遞給拆

my_list = string.split('=') 

所以這個分裂的=您的字符串簽署部分拆分值將字符串分解被收集在一個名單

my_list = ['<node> user ', ' "bob" password ', '"123" </node> <node> user ', ' "john" password ', '"123" </node> <node> user ', ' "will" password ', '"1234" </node> <node> user ', ' "andrew" password ', '"12345" </node> <node> user ', ' "mike" password ', '"123456" </node>'] 

如果你仔細看,名字都包含在也有字的密碼列表中的項目,所以我們將使用該規律來獲得下一步

names = [] # this will hold the names after we find them 
for item in my_list: 
    if 'password' not in item: 
     continue # if password is not in the item then we don't want to do anything so get the next item 
    name = item.strip().split(' ')[0] # get rid of the leading blank space (and trailing) then split on the blank space keep the first item in the resulting list 
    name = name.replace('"','') # I assume you want to get rid of the double quotes as they are not part of the name 
    names.append(name) 

現在的名字是一個名字列表

['bob', 'john', 'will', 'andrew', 'mike'] 
相關問題