Home > Blockchain >  how to keep every string from the first occurence of a number using python regex
how to keep every string from the first occurence of a number using python regex

Time:05-28

So, I have a list of elements like:

mylist=["AAA M640-305-168", "BBB CC R M450-20 M"]

and I want to keep:

output_1=["640-305-168", "450-20 M"]

And also:

output_2=["640-305-168", "450-20"]

Note that for the last requirement, only the numbers and hyphens have been kept. Is there and way to achieve this using regex in python? Thanks in advance!

CodePudding user response:

Heres a one-liner w/o use of regex:

>>> mylist=["AAA M640-305-168", "BBB CC R M450-20 M"]
>>> [w.lstrip('M') for e in mylist for w in e.split() if w.lstrip('M').replace('-', '').isnumeric()]
['640-305-168', '450-20']

CodePudding user response:

Using a regex in a list comprehension (requires python≥3.8 for the walrus operator):

mylist=["AAA M640-305-168", "BBB CC R M450-20 M"]

import re

output_1 = [m.group(0) if (m:=re.search(r'\d.*', s)) else s for s in mylist]
# ['640-305-168', '450-20 M']

output_2 = [m.group(0) if (m:=re.search(r'[\d-] ', s)) else s for s in mylist]
# ['640-305-168', '450-20']
  • Related