Python Forum

Full Version: Help with a regular expression
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi guys, 
Hoping somebody can help me here. I have a list of email messages and their UID's. I need to use re.findall() to select just the UID from the list. 

The format of the input is:
b' +OK 1 19
b' +OK 2 22
b' +OK 3 25
etc.
Now, I can use this re to return the below format, 
messageUID = re.findall(r'\d+ \d+',messageUID,0)[0]
{msgNum UID}:
1 19
2 22
3 25
4 28
5 35
However, I'm trying to retrieve just the UID (19, 22, 25, 28... etc)
Which is the 2nd occurrence of r' \d+'

​​​​​​​How can I do this?
First of all, if your input is as regular as you show, I would not use the regex and just split() it.

uid = messageUID.split()[-1]
But if it's useful for other reasons, use parenthesis to change the second digit block into a group.  Then the 0th element will refer to that group.

>>> re.findall(r'\d+ \d+',' +OK 1 19',0)[0]
'1 19'
>>> re.findall(r'\d+ (\d+)',' +OK 1 19',0)[0]
'19'
(Oct-13-2020, 03:55 PM)bowlofred Wrote: [ -> ]First of all, if your input is as regular as you show, I would not use the regex and just split() it.

uid = messageUID.split()[-1]
But if it's useful for other reasons, use parenthesis to change the second digit block into a group.  Then the 0th element will refer to that group.

>>> re.findall(r'\d+ \d+',' +OK 1 19',0)[0]
'1 19'
>>> re.findall(r'\d+ (\d+)',' +OK 1 19',0)[0]
'19'
Thanks for the suggestion. 
I just found that selecting the second item from the list like this, also gives me what I want. I will try your suggestions if I continue to run into trouble!
 
messageUID=re.findall(r'\d+',messageUID,0)[1]