[英]How to get a specific number part from a string using regex
result = ['\nR0 16082219 16.9(5r) ']
我需要将“16082219”放入变量中。 请帮助我使用 python 中的正则表达式。 我尝试了很多东西,但没有奏效。
你的问题并不完全正确。 你要买什么? 8位数字的序列? 空格之间的数字? 第二个字? 行尾的第二个单词? 查看python3的几个答案,他们都会使用完全不同的正则表达式找到相同的东西。
import re
result = ['\nR0 16082219 16.9(5r) ']
re_d8 = re.compile(r'(?P<d8>\d{8})')
m_d8 = re_d8.search(result[0]) # search for eight digits
if m_d8:
print(f"d8={m_d8.group('d8')}")
re_2 = re.compile(r'[^ ]+ +(?P<digits>\d+) +') # search for second word which contains only digits
m_2 = re_2.search(result[0])
if m_2:
print(f"digits={m_2.group('digits')}")
re_3 = re.compile(r'(?P<d3>\d+) [^ ]+ $') # search for the second word from the end
m_3 = re_3.search(result[0])
if m_3:
print(f"d3={m_3.group('d3')}")
re_sDs = re.compile(r' (?P<sds>\d+) ') # search for numbers between spaces
m_sds = re_sDs.search(result[0])
if m_sds:
print(f"sds={m_sds.group('sds')}")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.