我遇到以下python的一些问题。我试图匹配单引号内的字符串,但只捕获内容,即删除单引号本身。
In [144]: tststr = "'hello'"
In [145]: res = re.search(r"'(.*)'", tststr)
In [146]: res.group()
Out[146]: "'hello'"
我希望输出只包含"你好"没有单引号。
感谢您的帮助!
答案 0 :(得分:3)
您需要指定实际存储捕获字符的组的组索引号。如果没有索引号,res.group()
将打印您案例中所有匹配的字符,它是'hello'
。
res.group(1)
例如:
>>> tststr = "'hello'"
>>> res = re.search(r"'(.*)'", tststr)
>>> res.group(1)
'hello'