如何将正则表达式匹配的一部分作为python中的变量? [英] How can I get part of regex match as a variable in python?

查看:19
本文介绍了如何将正则表达式匹配的一部分作为python中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Perl 中可以做这样的事情(我希望语法是正确的...):

$string =~ m/lalala(我想要这部分)lalala/;$whatIWant = $1;

我想在 Python 中做同样的事情,并以 $1 之类的字符串获取括号内的文本.

解决方案

参见:Python 正则表达式匹配对象

<预><代码>>>>进口重新>>>p = re.compile("lalala(我想要这部分)lalala")>>>p.match("lalala我想要这个partlalala").group(1)'我想要这部分'

In Perl it is possible to do something like this (I hope the syntax is right...):

$string =~ m/lalala(I want this part)lalala/;
$whatIWant = $1;

I want to do the same in Python and get the text inside the parenthesis in a string like $1.

解决方案

See: Python regex match objects

>>> import re
>>> p = re.compile("lalala(I want this part)lalala")
>>> p.match("lalalaI want this partlalala").group(1)
'I want this part'

这篇关于如何将正则表达式匹配的一部分作为python中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆