我需要从如下字符串中提取一个矩阵(它可以是一个更大的矩阵):
[[13,2,99][-2,3,13][1,3,0][7,77,777]]我想将所有查找子字符串的列表与我在regexr.com上测试的正则表达式匹配,这个表达式给出了我想要的匹配,但不是在pythex.org或脚本中。
下面是使用regex的示例代码:
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)发布于 2020-08-17 05:33:20
正则表达式中的捕获括号导致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]']发布于 2020-08-17 05:51:21
您可以在其中插入一些逗号,然后json.loads它:
json.loads(matrix.replace('][', '],['))发布于 2020-08-17 05:13:14
试着使用
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)输出:
[array([13, 2, 99]), array([-2, 3, 13]), array([1, 3, 0]), array([ 7, 77, 777])]无瘤
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)输出:
[[13, 2, 99], [-2, 3, 13], [1, 3, 0], [7, 77, 777]]https://stackoverflow.com/questions/63444786
复制相似问题