2017-06-20 64 views
0

a。我有一個線以下給出:如何在Python中匹配字符串後打印所有字符串

HELLO CMD-LINE: hello how are you -color blue how is life going -color red,green life is pretty -color orange,violet,red 

灣我想在-color之後打印字符串。

c。我想下面的REG EXP方法,

for i in range (len(tar_read_sp)): 
print tar_read_sp[i] 
wordy = re.findall(r'-color.(\w+)', tar_read_sp[i], re.M|re.I|re.U) 
# print "%s"%(wordy.group(0)) 
if wordy: 
    print "Matched" 
    print "Full match: %s" % (wordy) 
    print "Full match: %s" % (wordy[0]) 
    # wordy_ls = wordy.group(0).split('=') 
    # print wordy_ls[1] 
    # break 
else: 
    print "Not Matched" 

但它的字符串後僅列第一個字匹配一樣, ['blue', 'red', 'orange']

c。但如何匹配字符串後打印所有的字符串?像 ['blue', 'red', 'green', 'orange', 'violet']並刪除重複的變量?

請分享您的意見和建議以便打印相同內容?

+0

解決您的壓痕.....嘗試' (?: - color。((?:\ w +,?)+))'然後使用split() – depperm

回答

0

同意depperm:修復您的縮進。

用他的正則表達式的建議,並提供必要的拆分,移除重複合併和重新排序列表:

wordy = re.findall(r'(?:-color.((?:\w+,?)+))', test_string, re.M|re.I|re.U) 
wordy = list({new_word for word in wordy for new_word in word.split(',')})[::-1] 

這應該給你一個扁平化的,獨特的名單就像你問(至少我想這就是你的意思是「刪除重複變量」)。

0

我個人的偏好會做這樣的事情:

import re 

tar_read_sp = "hello how are you -color blue how is life going -color red,green life is pretty -color orange,violet,red" 

wordy = re.findall(r'-color.([^\s]+)', tar_read_sp, re.I) 

big_list = [] 
for match in wordy: 
    small_list = match.split(',') 
    big_list.extend(small_list) 

big_set = list(set(big_list)) 
print (big_set) 

我發現這個方法有點更容易閱讀和更新的道路。這個想法是獲得所有這些顏色匹配,建立一個大名單,並使用設置去重複它。我使用的正則表達式:

-color ([^\s])+ 

將捕獲的顏色了下一個空格「small_list」。

0

我有一個不使用正則表達式的解決方案。

test_string = 'hello how are you -color blue how is life going -color red,green life is pretty -color orange,violet,red' 
result = [] 
for colors in [after_color.split(' ')[1] for after_color in test_string.split('-color')[1:]]: 
    result = result+colors.split(',') 
print result 

結果是: [ '藍色', '紅色', '綠色', '橙色', '紫色', '紅色']

相關問題