2017-04-17 68 views
0

我有一个这样的字符串,如何使用“[”作为在Python正则表达式的象征

a = '''hai stackoverflow. <help>//(good evening): value ="[i am new to 'python'], i need help"</help>''' 

从这个字符串,我需要将部分字符串提取<help></help>。 这意味着,我的输出应该是

<help>//(good evening): value ="[i am new to 'python'], i need help"</help> 

我试图用这个表达

re.search(r'<help> [\w:=">/-/\[\]]*',a).group() 

,但我得到错误的

Traceback (most recent call last): 
    File "<pyshell#467>", line 1, in <module> 
    re.search(r'<help> [\w:=">/-/\[\]]*',a).group() 
AttributeError: 'NoneType' object has no attribute 'group' 
+2

包含您遇到的错误。 –

+2

... *什么*错误?你有没有尝试使用正则表达式调试器,如http://regex101.com? – jonrsharpe

+1

*我得到错误*是一个无用的问题描述,除非你告诉我们你得到了什么*错误*。它在你的屏幕上,就在眼前。绝对没有任何借口**,因为你没有在你的文章中加入它。 –

回答

2

你得到一个AttributeError因为re.search回报None ,所以它没有group()方法。
如果改变这一行:

re.search(r'<help> [\w:=">/-/\[\]]*',a).group() 

这样:

search_result = re.search(r'<help> [\w:=">/-/\[\]]*',a) 
if search_result : 
    search_result = search_result.group() 

你将摆脱的AttributeError

您可以\转义字符,但在这种情况下,你可以得到结果要容易得多:

print(re.search('<help>(.*?)</help>', a).group()) 
<help>//(good evening): value ="[i am new to 'python'], i need help"</help> 
+0

Thankyou,这个答案很有帮助。 – sowji

相关问题