2017-07-14 44 views
1

我有一個字符串列表,我想通過部分匹配該子字符串,直到一個空白字符串中提取匹配的字符串中的標記。Python的正則表達式匹配項中的字符串和返回項目,如果子項存在

l=[u'i like cats and dogs',u'i like catnip plant', u'i like cars'] 
for s in l: 
    if "cat" in s: 
     #match cat until whitespace 
     print re.search("(cat).*[^\s]+",s).groups() 

然而這僅返回貓:

(u'cat',) 
(u'cat',) 

我想:

cats 
catnip 

回答

0

聽起來像是你要匹配以 '貓' 開頭的字:

import re 
l=[u'i like cats and dogs',u'i like catnip plant', u'i like cars'] 
for s in l: 
    if "cat" in s: 
     print re.search("cat\w*",s).group() 

這將返回:

cats 
catnip 

您還可以使用:

print re.search("cat[^\s]*",s).group() 

print re.search("cat\S*",s).group() 

詳細信息:

你的這些問題與你的正則表達式:"(cat).*[^\s]+"。首先,你只是將「貓」分組,因爲它是括號中唯一的子字符串,所以當你使用.groups()打印比賽中的組時,你只打印「貓」。第二個是.*,跟在(cat)之後,匹配零個或多個包含空格的任何字符,所以正則表達式匹配整個字符串,然後進入「not a space」字符匹配[^\s]

另一個問題是您正在使用.groups(),它返回一個包含匹配中所有組的元組。在你的情況下,你只有一個組,所以它返回一個只有一個組的元組。例如:

l=[u'i like cats and dogs',u'i like catnip plant', u'i like cars'] 
for s in l: 
    if "cat" in s: 
     print re.search("(cat\w*)",s).groups() 

返回這些元組(每個只有一組):

(u'cats',) 
(u'catnip',) 

既然你只有你並不需要一個元組一個組,所以你可以使用.group()

print re.search("(cat\w*)",s).group() 

它返回只匹配組:

cats 
catnip 

此外,由於該組是整個比賽,因此您不需要對其進行分組(即。你不需要括號)。 .group()默認爲.group(0)返回了全場比賽:你想要什麼

print re.search("cat\w*",s).group() 

打印。

最後,要注意後\w[^\s]\S也使其詞cat匹配*使用。

0

我覺得你只是想catre.search(r"cat\S*",s)後匹配任何非空白字符就足夠了這。

import re 
l=[u'i like cats and dogs',u'i like catnip plant', u'i like cars'] 
for s in l: 
    #match cat until whitespace 
    m = re.search(r"cat\S*",s) 
    if m: 
     print(m.group()) 

Python demo

的模式匹配:

  • cat - 一個cat
  • \S* - 0個或多個非空白字符(如果你只需要匹配,替換爲[^\W\d_]*模式)。

爲了使圖案不區分大小寫,通過re.I標誌提供給re.search方法,或在模式的開始添加(?i)直列改性劑版本。

相關問題