0

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)
1
  • 1
    You should add .group(0) to the end of the var line Commented Apr 2, 2014 at 10:22

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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'

Comments

0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.