[英]Use python re.findall to split the line
I am trying to use re.findall to split one string:我正在尝试使用 re.findall 拆分一个字符串:
string = '1.1 2 -4259.8774 0.000000 0.707664 0.002210 -0.004314-0.004912-0.000823'
I tried with:我试过:
match = re.findall(r'-?\d+\.?\d+m?', string)
but I got:但我得到了:
['1.1', '-4259.8774', '0.000000', '0.707664', '0.002210', '-0.004314', '-0.004912',
'-0.000823']
The second string '2' is missing.缺少第二个字符串“2”。 What I want is:
我想要的是:
['1.1', '2', '-4259.8774', '0.000000', '0.707664', '0.002210', '-0.004314', '-0.004912',
'-0.000823']
I would use re.findall
here:我会在这里使用
re.findall
:
string = '1.1 2 -4259.8774 0.000000 0.707664 0.002210 -0.004314-0.004912-0.000823'
nums = re.findall(r'(?:\b|-)\d+(?:\.\d+)?', string)
print(nums)
This prints:这打印:
['1.1', '2', '-4259.8774', '0.000000', '0.707664', '0.002210', '-0.004314', '-0.004912',
'-0.000823']
Here is an explanation of the regex pattern:以下是正则表达式模式的解释:
(?:\b|-) match either a word boundary OR a minus sign, which is followed by
\d+(?:\.\d+)? a whole number with optional decimal component
The idea here is that the left boundary of each number is either a \b
word boundary, or the number starts with a minus sign.这里的想法是每个数字的左边界是
\b
单词边界,或者数字以减号开头。
Just do:做就是了:
match = re.findall( r'-?\d+\.?\d*m?' , string)
You accounted for missing the .
你占了丢失的
.
, but not for anything following it. ,但不适用于其后的任何内容。 So with
\d*
, we fix it.所以使用
\d*
,我们修复它。
This worked for me you can check and let me know if something else that you need这对我有用,您可以检查并让我知道您是否需要其他东西
import re
string='1.1 2 -4259.8774 0.000000 0.707664 0.002210 -0.004314-0.004912-0.000823'
match = re.findall( r'-?\d*\.?\d+m?' , string)#After first \d i replace "+" with "*"
Output Output
['1.1',
'2',
'-4259.8774',
'0.000000',
'0.707664',
'0.002210',
'-0.004314',
'-0.004912',
'-0.000823']
You can simply combine two regex patterns to filter out the desired numbers as below:您可以简单地结合两个正则表达式模式来过滤掉所需的数字,如下所示:
import re
>>> string='1.1 2 -4259.8774 0.000000 0.707664 0.002210 -0.004314-0.004912-0.000823'
>>> re.findall('-?\d+.?\d+|\d+', string)
>>> ['1.1', '2', '-4259.8774', '0.000000', '0.707664', '0.002210', '-0.004314', '-0.004912', '-0.000823']
In the first pattern -?\d+.?\d+
the在第一个模式中
-?\d+.?\d+
-?\d+.?
- Fetches any integer whether or not a negative fraction exists. - 获取任何 integer,无论是否存在负分数。 For instance, it matches
-0.
例如,它匹配
-0.
\d+
- Fetches the digit after the decimal \d+
- 获取小数点后的数字
In the second pattern在第二个模式
\d+
- Fetches any whole numbers. \d+
- 获取任何整数。 For example, 2
, 3
, 15
etc. 3
, 2
15
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.