如何在python中获取部分正则表达式匹配作为变量?

如何在python中获取部分正则表达式匹配作为变量?,python,regex,perl,Python,Regex,Perl,在Perl中,可以执行以下操作(我希望语法正确……): 我想在Python中也这样做,并将括号内的文本放在一个类似$1的字符串中 import re data = "some input data" m = re.search("some (input) data", data) if m: # "if match was successful" / "if matched" print m.group(1) 查看以了解更多信息。请参阅: 一个小提示:在Perl中,当您编写 $string

在Perl中,可以执行以下操作(我希望语法正确……):

我想在Python中也这样做,并将括号内的文本放在一个类似$1的字符串中

import re
data = "some input data"
m = re.search("some (input) data", data)
if m: # "if match was successful" / "if matched"
  print m.group(1)
查看以了解更多信息。

请参阅:

一个小提示:在Perl中,当您编写

$string =~ m/lalala(.*)lalala/;

regexp可以匹配字符串中的任何位置。等效的方法是使用
re.search()
函数,而不是
re.match()
函数,该函数要求模式匹配从字符串开头开始。

如果要按名称获取零件,也可以这样做:

>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcom Reynolds")
>>> m.groupdict()
{'first_name': 'Malcom', 'last_name': 'Reynolds'}
m=re.match(r“(?P\w+(?P\w+)”,“马尔科姆雷诺”) >>>m.groupdict() {'first_name':'Malcom','last_name':'Reynolds'}
该示例取自

,不需要正则表达式。简单想想

>>> "lalala(I want this part)lalala".split("lalala")
['', '(I want this part)', '']
>>> "lalala(I want this part)lalala".split("lalala")[1]
'(I want this part)'
>>>
在试图将一个Perl程序转换为Python来解析模块外的函数名时,我遇到了这个问题,我收到了一个错误,说“group”未定义。我很快意识到抛出异常是因为p.match/p.search如果没有匹配的字符串,则返回0

因此,group运算符不能在其上运行。因此,为了避免出现异常,请检查是否存储了匹配项,然后应用group运算符

import re

filename = './file_to_parse.py'

p = re.compile('def (\w*)')            # \w* greedily matches [a-zA-Z0-9_] character set


for each_line in open(filename,'r'):
    m = p.match(each_line)             # tries to match regex rule in p
    if m:
        m = m.group(1)
        print m

非常聪明的想法:)
$string =~ m/lalala(.*)lalala/;
>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcom Reynolds")
>>> m.groupdict()
{'first_name': 'Malcom', 'last_name': 'Reynolds'}
>>> "lalala(I want this part)lalala".split("lalala")
['', '(I want this part)', '']
>>> "lalala(I want this part)lalala".split("lalala")[1]
'(I want this part)'
>>>
import re

string_to_check = "other_text...lalalaI want this partlalala...other_text"

p = re.compile("lalala(I want this part)lalala")    # regex pattern
m = p.search(string_to_check)                       # use p.match if what you want is always at beginning of string

if m:
    print m.group(1)
import re

filename = './file_to_parse.py'

p = re.compile('def (\w*)')            # \w* greedily matches [a-zA-Z0-9_] character set


for each_line in open(filename,'r'):
    m = p.match(each_line)             # tries to match regex rule in p
    if m:
        m = m.group(1)
        print m