[英]How to extract digits from string and return the last 3 or less using regex
[英]Extract last sequence of digits from string along with everything that precede it
考慮以下字符串:
AB01CD03
我想做的是把它分解成兩個令牌,即 AB01CD 和 03。
在我的字符串中,最后一個字母字符后面的位數是未知的。 字符串末尾總是有一個數字序列。
現在,我可以這樣做:
import re
S = 'AB01CD03'
v, = re.findall(r'(\d+)$', S)
assert v == '03'
...並且因為我現在知道v的長度,所以我可以推斷出如何使用切片獲取前導碼 - 例如,
preamble = S[:-len(v)]
assert preamble == 'AB01CD'
請記住序言可能包含數字,我正在尋找的是一個單一的 RE,它將顯示兩個單獨的令牌 - 即,
a, b = re.findall(MAGIC_EXPRESSION, S)
這可能嗎?
是的,像這樣:
import re
s = 'AB01CD03'
m = re.match(r'^(.+?)(\d+)$', s)
print(m.group(1), m.group(2))
這是有效的,因為組(.+?)
不是貪婪的,因此允許第二組(\d+)
匹配末尾的所有數字。 ^
和$
確保組分別位於開始和結束。
結果:
AB01CD 03
更接近您要求的語法:
a, b = re.match(r'^(.+?)(\d+)$', s).groups()
你可以使用這個:
import re
ls = ['AB01CD03', 'AB34565701CD04564563']
for s in ls:
a, b = re.findall(r'(.*(?:\D|^))(\d+)', s)[0]
print(a,b)
Output:
AB01CD 03
AB34565701CD 04564563
(.*(?:\D|^))(\d+)
第一個捕獲組 (.*(?:\D|^))
.
匹配任何字符(行終止符除外)
*
在零次和無限次之間匹配前一個令牌,
盡可能多次,根據需要回饋(貪婪)
非捕獲組(?:\D|^)
第一種選擇\D
\D
匹配任何不是數字的字符(相當於 [^0-9]) 第二種選擇^
^
在行首斷言 position 第二捕獲組(\d+)
\d
匹配一個數字(相當於 [0-9])
+
匹配前一個令牌一次到無限次,盡可能多次,根據需要回饋(貪婪)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.