使用 re 匹配 python 中的数字

Match number in python using re

我有很多数据以这种形式写入(从文件中读取):

(31265+0j)
(-5613.54281374+404.957401125j)
(1371.65134844+2671.06617046j)
...

然而我想提取数字部分,比如 [31265, 0][-5613.54281374 , 404.957401125] ,我按照我认为可行的方式在 python 中编码:

re.findall(r'.*([\+|\-]?\d+.?\d+)([\+|\-]?\d+.?\d+).*', tempStr)

但它不起作用,它给了我这个:

[]
[('26', '5+0')]
[('11', '25')]
...

有什么问题吗?是关于惰性模式的吗?我该如何解决?

========================更新==================== ==== 对我来说,这个问题已经解决了,但我仍然想知道正则表达式部分有什么问题,有没有人愿意帮我指出正则表达式模式有什么问题?

这些是数字。你不应该在这里使用正则表达式。第一部分是 real 第二部分是 imaginary 你可以像这样访问它们

 n = (-5613.54281374+404.957401125j)
 n.real
 n.imag

一开始可能很难发现,因为在数学中我们经常使用 i = sqrt(-1) 但在 python 中它是 j = sqrt(-1) 但是有趣的是,如果你这样做

import math
math.sqrt(-1) 

你会得到一个ValueError

更新:

如果数据在文件中

with open('complex.txt') as f:
    for line in f:
        number = complex(line.strip())

更新二: 如果您真的非常非常想使用正则表达式:

 map(float, line[1:-2].split('+'))

如果复数部分可能为负数,请改用 re.split()。

使用 .real 和 .imag 会给你想要的输出

   foo = (31265 + 0j)
   bar = [foo.real , bar.imag]
   #>>>[31265.0 , 0.0]