Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert regexp to python from perl

Tags:

python

regex

perl

in Perl:

 if ($test =~ /^id\:(.*)$/ ) {

 print $1;

 }
like image 921
Bdfy Avatar asked Dec 01 '22 04:12

Bdfy


2 Answers

In Python:

import re

test = 'id:foo'

match = re.search(r'^id:(.*)$', test)
if match:
    print match.group(1)

In Python, regular expressions are available through the re library.

The r before the string indicates that it is a raw string literal, meaning that backslashes are not treated specially (otherwise every backslash would need to be escaped with another backslash in order for a literal backslash to make its way into the regex string).

I have used re.search here because this is the closest equivalent to Perl's =~ operator. There is another function re.match which does the same thing but only checks for a match starting at the beginning of the string (counter-intuitive to a Perl programmer's definition of "matching"). See this explanation for full details of the differences between the two.

Also note that there is no need to escape the : since it is not a special character in regular expressions.

like image 148
Cameron Avatar answered Dec 04 '22 22:12

Cameron


match = re.match("^id:(.*)$", test)
if match:
    print match.group(1)
like image 25
Novikov Avatar answered Dec 05 '22 00:12

Novikov