【问题标题】:Extract substring with regex python [duplicate]用正则表达式python提取子字符串[重复]
【发布时间】:2017-04-20 20:25:23
【问题描述】:

我知道这是一个非常常见的问题,但它让我发疯了。

我想使用正则表达式来匹配字符串中的子字符串。

 line = '##ParameterValue[part I care about]=garbagegarbage'

我想提取part I care about。 我的代码如下所示:

import re
line = '##ParameterValue[part I care about]=garbagegarbage'
m = re.match('\[(.*)\]', line)
print m.group(1)

但这给了我一个AttributeError: 'NoneType' object has no attribute 'group'

我在regex101 上测试了我的正则表达式,它可以工作。我不明白为什么这对我来说失败了。

【问题讨论】:

  • 你说得对,这个问题太频繁了。
  • 改用searchmatch 正在寻找从字符串的开头匹配。

标签: python regex


【解决方案1】:

match 更改为search

import re
line = '##ParameterValue[part I care about]=garbagegarbage'
m = re.search('\[(.*)\]', line)
print m.group(1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-28
    相关资源
    最近更新 更多