2010-06-02 61 views
2

我開始使用正則表達式,我想知道,如果有人可以幫助我的手藝轉換座標如下語句替換「 **」以斷行:使用正則表達式(或別的東西)

145.00694,-37.80421,9 145.00686,-37.80382,9 145.00595,-37.8035,16 145.00586,-37.80301,16 

145.00694,-37.80421 
145.00686,-37.80382 
145.00595,-37.8035 
145.00586,-37.80301 

(剝去最後一個逗號和值,並把它變成一個換行符。)

我無法弄清楚如何使用通配符做這樣的事情。任何幫助將不勝感激!謝謝。

+0

我用這個http://www.regexlib.com/CheatSheet.aspx在過去用於編寫正則表達式,這是非常有幫助的。 – VoodooChild 2010-06-02 08:29:28

回答

3

「有些人,當與 面臨的問題,認爲‘我知道,我將使用 正則表達式。’現在他們有 兩個問題。「 - Jamie Zawinski

避免這一問題,使用字符串方法:

s="145.00694,-37.80421,9 145.00686,-37.80382,9 145.00595,-37.8035,16 145.00586,37.80301,16" 

lines = s.split(' ') # each line is separated by ' ' 
for line in lines: 
    a,b,c=line.split(',') # three parts, separated by ',' 
    print a,b 

正則表達式有其用途,但這不是其中之一。

2
>>> import re 
>>> s="145.00694,-37.80421,9 145.00686,-37.80382,9 145.00595,-37.8035,16 145.00586,-37.80301,16" 
>>> print re.sub(",\d*\w","\n",s) 
145.00694,-37.80421 
145.00686,-37.80382 
145.00595,-37.8035 
145.00586,-37.80301 
+0

很棒!非常感謝! – John 2010-06-02 08:37:55

+0

這又是一個非常脆弱的正則表達式的好例子:只有在第二個數字(-37.X)是負數時才起作用... – 2010-06-02 08:42:05

+0

是的,我剛剛注意到...如何修改它以使其成爲匹配「,[兩位數字] [空格]」?我正在嘗試「\ d \ d \ w」但這似乎不起作用。 – John 2010-06-02 08:46:56

1

字符串的方法似乎這裏就夠了,正則表達式是矯枉過正:

>>> s='145.00694,-37.80421,9 145.00686,-37.80382,9 145.00595,-37.8035,16 145.00586,-37.80301,16' 
>>> print('\n'.join(line.rpartition(',')[0] for line in s.split())) 
145.00694,-37.80421 
145.00686,-37.80382 
145.00595,-37.8035 
145.00586,-37.80301 
0
>>> s = '145.00694,37.80421,9 145.00686,-37.80382,9 145.00595,-37.8035,16 145.00586,-37.80301,16 
>>> patt = '(%s,%s),%s' % (('[+-]?\d+\.?\d*',)*3) 
>>> m = re.findall(patt, s) 
>>> m 
['145.00694,37.80421', '145.00686,-37.80382', '145.00595,-37.8035', '145.00586,-37.80301'] 
>>> print '\n'.join(m) 
145.00694,37.80421 
145.00686,-37.80382 
145.00595,-37.8035 
145.00586,-37.80301 

但我更喜歡使用正則表達式在這種情況下

我喜歡SilentGhost解決方案

相關問題