簡體   English   中英

python 中的正則表達式不匹配

[英]Regular expression not matching in python

我需要從一個看起來像這樣的字符串中提取一個矩陣(它可以是一個更大的矩陣):

[[13,2,99][-2,3,13][1,3,0][7,77,777]]

我想將所有查找列表的子字符串與我在 regexr.com 上測試的正則表達式匹配,這給了我想要的匹配,但在 pythex.org 或我的腳本中沒有

這是使用正則表達式的示例代碼:

import numpy as np
import re
matrix = "[[13,2,99][-2,3,13][1,3,0][7,77,777]]"
l = []
regex = re.compile(r"\[(-?[0-9]+,)+-?[0-9]+]")
for el in re.findall(regex, matrix):
    l.append(np.fromstring(el[1:len(el)-1], dtype=int, sep=",").tolist())
a = np.array(l)

您可以在其中插入一些逗號,然后 json.loads 它:

json.loads(matrix.replace('][', '],['))

正則表達式中的捕獲括號導致re.findall僅返回帶括號的子匹配。 切換到非分組括號修復它。

Python 3.8.2+ (heads/3.8:686d508, Mar 26 2020, 09:32:57) 
[Clang 11.0.3 (clang-1103.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> matrix = "[[13,2,99][-2,3,13][1,3,0][7,77,777]]"
>>> regex = re.compile(r"\[(-?[0-9]+,)+-?[0-9]+]")
>>> re.findall(regex, matrix)
['2,', '3,', '3,', '77,']
>>> regex = re.compile(r"\[(?:-?[0-9]+,)+-?[0-9]+]")
>>> re.findall(regex, matrix)
['[13,2,99]', '[-2,3,13]', '[1,3,0]', '[7,77,777]']

嘗試使用

import re
import numpy as np

s = "[[13,2,99][-2,3,13][1,3,0][7,77,777]]"
l = []
for i in re.findall(r"(\[.*?\])", s):    # Find everything inside [] brackets. 
    l.append(np.fromstring(i.strip("[]"), dtype=int, sep=","))
    
print(l)

Output:

[array([13,  2, 99]), array([-2,  3, 13]), array([1, 3, 0]), array([  7,  77, 777])]

不帶 numpy

import re

s = "[[13,2,99][-2,3,13][1,3,0][7,77,777]]"
l = []
for i in re.findall(r"(\[.*?\])", s):
    l.append(list(map(int, i.strip("[]").split(","))))
    
print(l)

Output:

[[13, 2, 99], [-2, 3, 13], [1, 3, 0], [7, 77, 777]]

除了缺少逗號之外,這看起來很像列表列表。 有多種按摩和分裂方式。

In [72]: astr = "[[13,2,99][-2,3,13][1,3,0][7,77,777]]"                                              

去掉外括號

In [75]: astr.strip('[]')                                                                            
Out[75]: '13,2,99][-2,3,13][1,3,0][7,77,777'

替換內部的,並立即拆分:

In [76]: astr.strip('[]').replace('][',';').split(';')                                               
Out[76]: ['13,2,99', '-2,3,13', '1,3,0', '7,77,777']

拆分那些內部字符串:

In [77]: [sub.split(',') for sub in _]                                                               
Out[77]: [['13', '2', '99'], ['-2', '3', '13'], ['1', '3', '0'], ['7', '77', '777']]

如果這些子列表的長度和數字字符串都相同,我們可以輕松地從這些子列表中創建一個數組(將 dtype 轉換為整數):

In [78]: np.array(_, int)                                                                            
Out[78]: 
array([[ 13,   2,  99],
       [ -2,   3,  13],
       [  1,   3,   0],
       [  7,  77, 777]])

暫無
暫無

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

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