簡體   English   中英

正則表達式獲取 Python 中兩個字符串之間的字符串

[英]Regular expression to get a string between two strings in Python

您能否建議如何提取{0}之間的字符串以及{字符串開頭並從右側被0覆蓋}和{字符串在末尾並從左側被0覆蓋}

'1001130001' -> [1,113,1]
'0001130001' -> [113,1]
'0001130000' -> [113]

編輯:我還需要每個字符串的位置。 (匹配對象)

我認為即使沒有正則表達式:

txts = ['1001130001', '0001130001', '0001130000']
for s in txts:
    print(list(map(int, filter(None, s.split('0')))))

如果您必須使用正則表達式,請嘗試:

import re
txts = ['1001130001', '0001130001', '0001130000']
for s in txts:
    print(list(map(int, re.findall(r'[1-9]+', s))))

兩個選項都返回:

[1, 113, 1]
[113, 1]
[113]

編輯:

既然你提到你還需要匹配 object 的 position,你可以使用re.finditer和一些列表理解:

import re
txts = ['1001130001', '0001130001', '0001130000']
for s in txts:
    print([[m.start(), int(m.group())] for m in re.finditer(r'[1-9]+', s)])

印刷:

[[0, 1], [3, 113], [9, 1]]
[[3, 113], [9, 1]]
[[3, 113]]

看起來您只想按零序列拆分。

>>> import re
>>> re.split('0+', '1001130001')
['1', '113', '1']

為了不以空結果結束,您可以使用str.strip預處理您的字符串。

>>> re.split('0+', '0001130000')
['', '113', '']
>>> re.split('0+', '0001130000'.strip('0'))
['113']

我更喜歡re.findall這里:

inp = ["1001130001", "0001130001", "0001130000"]
for val in inp:
    matches = re.findall(r'(?<![^0])[^\D0]+(?![^0])', val)
    print(matches)

這打印:

['1', '113', '1']
['113', '1']
['113']

以下是正則表達式模式的解釋:

(?<![^0])  assert that what precedes is either zero OR the start of the input
[^\D0]+    match one or more digit characters other than zero
(?![^0])   assert that what follows is either zero OR the end of the input

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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