Pythonizer
Pythonizer

Reputation: 1194

Python regex to get returned value from a string

Perl has some good and easy function to set the returned value to a variable

if($string =~ /<(\w+)>/){
     $name = $1;
}

This is what I tried for python and it works, but is there any alternative way of doing this?

if re.match('\s*<\w+>.+', string):
    var = re.findall('>(\w+)<', string)

Upvotes: 0

Views: 140

Answers (3)

Vasili Syrakis
Vasili Syrakis

Reputation: 9591

I don't think you regex will match anything. They both contradict each other.

This is how you would do a match in Python:

import re

string = "string"
matches = re.match('(\w+)', string)
print matches.group()

Upvotes: 0

piokuc
piokuc

Reputation: 26164

You don't need to do the match followed by findall, findall will return an empty list when there's no match:

>>> string = 'sdafasdf asdfas '
>>> var = re.findall('>(\w+)<', string)
>>> var
[]

So, you can translate your Perl example like this:

try: name = re.findall('>(\w+)<', string)[0]
except IndexError: name = 'unknown'

Upvotes: 0

Sabuj Hassan
Sabuj Hassan

Reputation: 39355

Hope this is what you looking for:

string = "id: 10"
match = re.search("id: (\d+)", string)
if match:
    id = match.group(1)
    print id

Whatever you need, you have possibly everything in Python re doc.

Upvotes: 3

Related Questions