[英]Extract numbers from a string while maintaining the whitespaces
我有一些這樣的字符串
' 12 2 89 29 11 92 92 10'
(所有的數字都是正整數所以沒-
沒有.
),我想從中提取所有的數字,編輯一些數字,然后把它們都具有相同的空格在一起。 例如,如果我將數字11
更改為22
,我希望最后一個字符串為
' 12 2 89 29 22 92 92 10'
我進行了一些搜索,大多數問題都忽略了空格,只關心數字。 我試過了
match = re.match((\s*(\d+)){8}, str)
但是match.group(0)
給了我整個字符串, match.group(1)
給了我第一個匹配\\ 12
(我加了\\
否則網站將不會顯示前導空格),以及match.group(2)
給我12
。 但是之后它不會給我任何數字,任何大於2
索引都會給我一個錯誤。 我認為我的方法不是正確的方法,正確的方法是什么?
我只是試過re.split('(\\d+)', str)
,這似乎是我所需要的。
我建議使用帶有非捕獲組的正則表達式,以獲取“空格”部分和“數字”部分的列表:
In [15]: text = ' 12 2 89 29 11 92 92 10'
In [16]: parts = re.findall('((?: +)|(?:[0-9]+))', text)
In [17]: parts
Out[17]: [' ', '12', ' ', '2', ' ', '89', ' ', '29', ' ',
'11', ' ', '92', ' ', '92', ' ', '10']
然后,您可以執行以下操作:
for index, part in enumerate(parts):
if part == '11':
parts[index] = '22'
replaced = ''.join(parts)
(或您要進行的任何匹配和替換)。
將所有數字與空格匹配,更改所需數字並加入數組。
import re
newNum = '125'
text = ' 12 2 89 29 11 92 92 10'
^^
marray = re.findall(r'\s+\d+', text)
marray[6] = re.sub(r'\d+', newNum, marray[6])
print(marray)
[' 12', ' 2', ' 89', ' 29', ' 11', ' 92', ' 125', ' 10']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.