簡體   English   中英

如何使用正則表達式從字符串中獲取特定數字部分

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM