Python中的Regex捕获组定义

2024-09-23 22:30:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我对下面的python有一些问题。我试图匹配单引号内的字符串,但只捕获内容,即删除单引号本身。你知道吗

In [144]: tststr = "'hello'"

In [145]: res = re.search(r"'(.*)'", tststr)

In [146]: res.group()
Out[146]: "'hello'"

我希望输出只包含“hello”而不包含单引号。你知道吗

谢谢你的帮助!你知道吗


Tags: 字符串inre内容hellosearchgroupres
1条回答
网友
1楼 · 发布于 2024-09-23 22:30:10

您需要指定实际存储捕获字符的组的组索引号。如果没有索引号,res.group()将打印您案例中所有匹配的字符,它是'hello'。你知道吗

res.group(1)

例如:

>>> tststr = "'hello'"
>>> res = re.search(r"'(.*)'", tststr)
>>> res.group(1)
'hello'

相关问题 更多 >