Python:RE问题“re.findall()”

时间:2014-01-16 06:04:28

标签: python regex python-2.7

string = "RegisterParameter uri wub {"
RegisterName = re.findall("RegisterParameter uri ([^ ]*) {",string)

print 'RegisterName is :',RegisterName

参见上面的代码。在这里,我想找到字符串中的寄存器名称,即正则表达式wub。我为此写了RE。如果你运行这段代码,它会给出像['wub']这样的输出,但我只希望wub不括号或引用。那么在这里做什么修改。

非常感谢你的帮助。

2 个答案:

答案 0 :(得分:3)

RegisterNamelist只有一个str元素。如果问题是只是打印,您可以尝试:

print 'RegisterName is :', RegisterName[0]

<强>输出:

RegisterName is : wub

PS:

  • 如果您不确定变量的类型,请尝试打印它:

    print type(RegisterName)
    
  • 我建议您使用Python conventions,名称如SomeName的标识符通常用作类的名称。对于变量,您可以使用some_nameregister_name

答案 1 :(得分:2)

您可以使用re.search()(或re.match() - 取决于您的需求)并获取捕获组:

>>> import re
>>> s = "RegisterParameter uri wub {"
>>> match = re.search("RegisterParameter uri ([^ ]*) {", s)
>>> match.group(1) if match else "Nothing found"
'wub'

此外,您可能希望使用[^ ]*而不是\w*\w匹配任何单词字符。

另见:

相关问题