gpt4 book ai didi

regex - 重新格式化整数 block (幻方)的正则表达式

转载 作者:行者123 更新时间:2023-12-01 10:46:22 26 4
gpt4 key购买 nike

正则表达式要求

我有一个包含幻方的大文件,四个一组,用空格分隔:

 2 16  1 15    10  5 12  7     9  3 14  8    13  6 11  4
14 9 8 3 3 9 8 14 5 10 7 12 12 10 7 5
11 4 13 6 6 4 13 11 16 15 2 1 1 15 2 16
7 5 12 10 15 16 1 2 4 6 11 13 8 3 14 9

最后我想找到并重新格式化这些组,以便每个单独的幻方分别显示如下:

 2 16  1 15
14 9 8 3
11 4 13 6
7 5 12 10

10 5 12 7
3 9 8 14
6 4 13 11
15 16 1 2

9 3 14 8
5 10 7 12
16 15 2 1
4 6 11 13

13 6 11 4
12 10 7 5
1 15 2 16
8 3 14 9

找出每组四位数字

首先,我有一个 Regex 可以找到所有由四个数字组成的组,但这只会给我需要的 16 个匹配项如果我指定每个整数前面有 0-2 个空格:

(( {0,2}\d{1,2}){4}).*?

( saved version on Regexr )

问题与解决方案

我只想捕获每列开头整数前的零个或一个空格,但不是分隔每个 16 block 的四个空格。

更大的问题

然后我需要捕获 16 组中的每组四个整数,并从捕获的组中重新格式化它们

\1\5\9\13\n\n

给予:

 2 16  1 15
14 9 8 3
11 4 13 6
7 5 12 10

但到目前为止我的正则表达式捕获了所有内容。我如何分离捕获组来实现这一点?

最佳答案

使用像python这样的脚本语言

这是我的解决方案。我认为效果很好。

squares = []
row_counter = 0
four = None
with open('magic-squares.txt') as f:
for row in f:
numbers = row.split()
if numbers:
if row_counter == 0:
if four:
squares += four
four = [[],[],[],[]]
for i in range(4):
four[i] += numbers[i*4:i*4+4]
row_counter += 1
row_counter %= 4

with open('output.txt', 'w') as f:
f.write('\n'.join(' '.join(square) for square in squares))

with open('output2.txt', 'w') as f:
f.write(
'\n\n'.join(
'\n'.join(
''.join(
["{:<2} ".format(item) for item in square[i*4:(i+1)*4]]
) for i in range(4)
) for square in squares
)
)

关于regex - 重新格式化整数 block (幻方)的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31631135/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com