How can I get part of regex match as a variable in python?

后端 未结 7 2048
梦毁少年i
梦毁少年i 2020-11-29 07:19

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;
7条回答
  •  佛祖请我去吃肉
    2020-11-29 08:05

    import re
    astr = 'lalalabeeplalala'
    match = re.search('lalala(.*)lalala', astr)
    whatIWant = match.group(1) if match else None
    print(whatIWant)
    

    A small note: in Perl, when you write

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

    the regexp can match anywhere in the string. The equivalent is accomplished with the re.search() function, not the re.match() function, which requires that the pattern match starting at the beginning of the string.

提交回复
热议问题