This question already has an answer here:
这个问题在这里已有答案:
- What is the difference between re.search and re.match? 7 answers
re.search和re.match有什么区别? 7个答案
I know this is a very frequently asked question, but it's driving me mad.
我知道这是一个非常常见的问题,但这让我很生气。
I want to use regex to match a substring in my string.
我想使用正则表达式匹配我的字符串中的子字符串。
line = '##ParameterValue[part I care about]=garbagegarbage'
And I would like to extract the part I care about
. My code looks like this:
我想提取我关心的部分。我的代码如下所示:
import re
line = '##ParameterValue[part I care about]=garbagegarbage'
m = re.match('\[(.*)\]', line)
print m.group(1)
But this gives me an AttributeError: 'NoneType' object has no attribute 'group'
但这给了我一个AttributeError:'NoneType'对象没有属性'group'
I tested my regex on regex101 and it works. I don't understand why this fails for me.
我在regex101上测试了我的正则表达式并且它有效。我不明白为什么这对我失败了。
1 个解决方案
#1
0
Change match
to search
将匹配更改为搜索
import re
line = '##ParameterValue[part I care about]=garbagegarbage'
m = re.search('\[(.*)\]', line)
print m.group(1)
#1
0
Change match
to search
将匹配更改为搜索
import re
line = '##ParameterValue[part I care about]=garbagegarbage'
m = re.search('\[(.*)\]', line)
print m.group(1)