Sarah
Sarah

Reputation: 463

how to extract token from string in python?

I'm pretty new to Python and I know Perl can do this, but I haven't found it in Python yet. What I'm trying to do is to extract a token from a line.

p = re.compile('555=\d+')
ID = p.findall(line)

where line is a single line in a file, and the digits after 555= should be recorded. However, with these two lines, I can only get things like 555=1234567, what I really want is 1234567. Can anyone help and suggest a solution? Thanks!

Upvotes: 5

Views: 9575

Answers (2)

Assem
Assem

Reputation: 12097

Use () to capture what you want:

>>> p = re.compile('555=(\d+)')
>>> p.findall("555=1234567")
['1234567']

(...)

Matches whatever regular expression is inside the parentheses, and indicates the start and end of a group; the contents of a group can be retrieved after a match has been performed, and can be matched later in the string with the \number special sequence

ref

Upvotes: 8

Lucas Infante
Lucas Infante

Reputation: 798

You should capture the expression you want using "()". So your expression should be p = re.compile('555=(\d+)')

Upvotes: 0

Related Questions