2011-06-06 36 views
0

是否有可能讀取re.search的輸出的長度?幫助re.search python length

例如:

import re 

list=['lost','post','cross','help','cost'] 

for i in range(len(list)): 
    output = re.search('os', list[i]) 

我可以讀輸出長度是多少?

+0

做***不*** ***使用正則表達式進行簡單的字符串比較。另外,迭代列表的正確方法是'for list in list'。請閱讀[Python教程](http://docs.python.org/tutorial/)。 – ThiefMaster 2011-06-06 22:36:49

+0

究竟是什麼長度? – 2011-06-06 22:37:05

+0

@ThiefMaster:我知道RE對於一個簡單的substing來說太多了,但是re.search比string.find更快,例如因爲它在第一次出現時停止。如果你有很多字符串,我更喜歡使用「異常」的方式,但要少一點時間。 – stdio 2011-06-06 22:47:25

回答

2

在這種情況下,輸出長度將與輸入長度相同,因爲您正在搜索特定的子字符串。當您在'lost'中搜索時,匹配的長度將爲2,因爲這就是搜索參數的長度。現在,如果您想區分「找到」和「未找到」,請記住,如果沒有匹配,則re.search返回None。如果你確實需要的長度,你可以這樣做:

for i in range(len(list)): 
    length = 2 if re.search('os', list[i]) else 0 

我建議你使用一個比較典型的foreach循環,但:

for item in list: 
    length = 2 if re.search('os', item) else 0 

如果你正在檢查一切是否會出現一個字符串在另一個內部,好了,你可以使用該in操作:

for item in list: 
    length = 2 if 'os' in item else 0 

現在,如果你正在尋找一個更復雜的正則表達式,你可以檢索組0 FR om匹配,這是整個子字符串,並檢查其長度:

for item in list: 
    match = re.search('[aeiou]s', item) 
    length = len(match.group(0)) if match else 0 
+0

現在,我明白什麼返回re.search輸出的長度...子字符串的長度!我很困惑,並且re.search不是我需要的。 – stdio 2011-06-06 22:53:25

0

re.search()返回一個具有span方法的匹配對象。此方法返回兩個元素,即匹配的開始位置和結束位置。

2

首先,爲內置的list分配一個新名字是一個非常糟糕的主意。其次,這不是迭代列表的一種非常Python的方式。所有的Python環路的for-each循環,所以簡單地做:

word_list = ['lost','post','cross','help','cost'] 
for word in word_list: 
    match = re.search("os", word) 

話雖這麼說,你可能尋找一個匹配的startend方法,它告訴你到底該商品的特定匹配文本開始正在被搜索,以及它在哪裏結束。

word_list = ['lost','post','cross','help','cost'] 
for word in word_list: 
    match = re.search("os", word) 
    if match is not None: 
     print match.start(), match.end() 

很明顯,長度的差別就是長度。給出你的單詞列表,這將打印

1 3 
1 3 
2 4 
1 3