in Perl:
if ($test =~ /^id\:(.*)$/ ) {
print $1;
}
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.
match = re.match("^id:(.*)$", test)
if match:
print match.group(1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With