1

Got the following string:

hash=49836EC32432A9B830BECFD66A9B6F936327EAE8

I need to match the 49836EC32432A9B830BECFD66A9B6F936327EAE8 so I do:

match = re.findall(".*hash=([A-F0-9]+).*",mydata)

all cool but when I want to print it

print "Hash: %s" % match

I get Hash: ['C5E8C500BA925237E399C44EFD05BCD4AAF76292']

what am I doing wrong? I need to print Hash: C5E8C500BA925237E399C44EFD05BCD4AAF76292

5 Answers 5

3
if match:
    print "Hash: %s" % match[0]
Sign up to request clarification or add additional context in comments.

Comments

3

findall gives you a list of all matches in the string. You are seeing exactly that - a list with the one match it found.

Try search instead: http://docs.python.org/2/library/re.html#re.search which returns a MatchGroup that you can get the first group of: http://docs.python.org/2/library/re.html#match-objects

Or you could do findall and use the first entry in the list to print (e.g. match[0]).

Comments

2

In your code, match is a list of strings resulting from the re.findall function ( [1]: http://docs.python.org/2/library/re.html). In this list, all matches are returned in the order found. In your case, the list only has one element, i.e. match[0].

Comments

2

It's simple:

In[1]: import re

In[2]: mydata = 'hash=49836EC32432A9B830BECFD66A9B6F936327EAE8'

In[3]: re.findall(".*hash=([A-F0-9]+).*",mydata)
Out[3]: ['49836EC32432A9B830BECFD66A9B6F936327EAE8'] # a list

In[4]: re.match(".*hash=([A-F0-9]+).*",mydata)
Out[4]: <_sre.SRE_Match at 0x5d79020>

In[5]: re.match(".*hash=([A-F0-9]+).*",mydata).groups()
Out[5]: ('49836EC32432A9B830BECFD66A9B6F936327EAE8',) # a tuple

In[6]: match = Out[3]

In[7]: print "Hash:",match[0] # so print the first item!!!
Hash: 49836EC32432A9B830BECFD66A9B6F936327EAE8

So in short, change the print line to:

if match:
    print "Hash: %s" % match[0] # only first element!!

Comments

0

It looks like it is not counting the value of match as a string. I don't have "mydata", but when I save hash as a string it prints out fine. It looks like you something there is not cast as a string, and I think it's the value of match. The quotes are indicating this has been cast as a string, I believe. Do type() to see what it is cast as, or try typing str(match) instead of match after your print statement.

Edit:

Someone else noted that it is returning an array value. Do match[0] to return the first value of the array.

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.