我开始使用RegEx,我想知道是否有人可以帮助我制作一个声明来转换坐标,如下所示:
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 :(得分: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
正则表达式有它们的用途,但这不是其中之一。
答案 1 :(得分: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
答案 2 :(得分: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
答案 3 :(得分: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解决方案