Reputation: 11
I am trying to get the last number from this string from each line but my code is only able to get '25' instead. I want to get 15, 10, 5, 5, and 25.
import re
string = """
1073811-S0-A M3S FRT SUBFRAME MNT FRT INR LH 15
1073851-S0-A M3S REAR QUARTER INNER LH 10
1080023-S0-C M3 ASY, COWL SIDE, LH 5
1080024-S0-C M3 ASY, COWL SIDE, RH 5
1080473-S0-B M3 ASY, SHOTGUN TOWER, LH 25
"""
qty = re.findall(r'\d{1,3}$', string)
print(qty)
Upvotes: 1
Views: 71
Reputation: 73
import re
str="""1073811-S0-A M3S FRT SUBFRAME MNT FRT INR LH 15
1073851-S0-A M3S REAR QUARTER INNER LH 10
1080023-S0-C M3 ASY, COWL SIDE, LH 5
1080024-S0-C M3 ASY, COWL SIDE, RH 5
1080473-S0-B M3 ASY, SHOTGUN TOWER, LH 25"""
pattern = re.compile(r'(?m)(\d+)\s*$')
match = pattern.findall(str)
for i in match:
print(i)
output is: 15 10 5 5 25
Upvotes: 0
Reputation: 22972
You can use the flag re.MULTILINE
:
qty = re.findall(r'\d{1,3}$', string, flags=re.MULTILINE)
You get: ['15', '5', '25']
But some line also ends with trailing white spaces. So, you can use a group with a optional white space:
qty = re.findall(r'(\d{1,3})\s*$', string, flags=re.MULTILINE)
You get: ['15', '10', '5', '5', '25']
.
You can also search the numbers which are followed by an optional white space and the end a string. You can do that with a positive lookhead:
qty = re.findall(r'\d{1,3}(?=\s*$)', string, flags=re.MULTILINE)
Upvotes: 2