簡體   English   中英

使用 python re.findall 分割線

[英]Use python re.findall to split the line

我正在嘗試使用 re.findall 拆分一個字符串:

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)

但我得到了:

['1.1', '-4259.8774', '0.000000', '0.707664', '0.002210', '-0.004314', '-0.004912',
 '-0.000823']

缺少第二個字符串“2”。 我想要的是:

['1.1', '2',  '-4259.8774', '0.000000', '0.707664', '0.002210', '-0.004314', '-0.004912',
 '-0.000823']

我會在這里使用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)

這打印:

['1.1', '2', '-4259.8774', '0.000000', '0.707664', '0.002210', '-0.004314', '-0.004912',
 '-0.000823']

以下是正則表達式模式的解釋:

(?:\b|-)       match either a word boundary OR a minus sign, which is followed by
\d+(?:\.\d+)?  a whole number with optional decimal component

這里的想法是每個數字的左邊界是\b單詞邊界,或者數字以減號開頭。

更新

做就是了:

match = re.findall( r'-?\d+\.?\d*m?'  , string)

你占了丟失的. ,但不適用於其后的任何內容。 所以使用\d* ,我們修復它。

這對我有用,您可以檢查並讓我知道您是否需要其他東西

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

['1.1',
 '2',
 '-4259.8774',
 '0.000000',
 '0.707664',
 '0.002210',
 '-0.004314',
 '-0.004912',
 '-0.000823']

您可以簡單地結合兩個正則表達式模式來過濾掉所需的數字,如下所示:

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']

在第一個模式中-?\d+.?\d+

-?\d+.? - 獲取任何 integer,無論是否存在負分數。 例如,它匹配-0.

\d+ - 獲取小數點后的數字

在第二個模式

\d+ - 獲取任何整數。 32 15

暫無
暫無

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

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