如何使用 python 正则表达式使每个字符串从第一次出现的数字开始
how to keep every string from the first occurence of a number using python regex
所以,我有一个元素列表,例如:
mylist=["AAA M640-305-168", "BBB CC R M450-20 M"]
我想保留:
output_1=["640-305-168", "450-20 M"]
还有:
output_2=["640-305-168", "450-20"]
请注意,对于最后一个要求,只保留了数字和连字符。在 python 中是否有使用正则表达式实现此目的的方法?提前致谢!
这里是 one-liner w/o 正则表达式的用法:
>>> 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']
在列表理解中使用正则表达式(walrus operator 需要 python≥3.8):
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']
所以,我有一个元素列表,例如:
mylist=["AAA M640-305-168", "BBB CC R M450-20 M"]
我想保留:
output_1=["640-305-168", "450-20 M"]
还有:
output_2=["640-305-168", "450-20"]
请注意,对于最后一个要求,只保留了数字和连字符。在 python 中是否有使用正则表达式实现此目的的方法?提前致谢!
这里是 one-liner w/o 正则表达式的用法:
>>> 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']
在列表理解中使用正则表达式(walrus operator 需要 python≥3.8):
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']