简体   繁体   中英

Multiline String Python Regex

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM