如何使用正则表达式从字符串中获取特定的数字部分

2024-04-20 10:14:57 发布

您现在位置:Python中文网/ 问答频道 /正文

result = ['\nR0        16082219            16.9(5r)                            ']

我需要将“16082219”放入一个变量中。请帮助我使用python中的正则表达式。我尝试了很多事情,但都没有成功


1条回答
网友
1楼 · 发布于 2024-04-20 10:14:57

你的问题不完全正确。你在找什么?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')}")

相关问题 更多 >