将正则表达式从两个步骤简化为一个步骤

时间:2016-09-04 16:01:04

标签: regex python-2.7 ironpython

我有以下字符串:

my_line = 'ps_args: com26:57600,    19-1125063, 1234, abc'

我希望最终结果是一个列表,如:

['com2:57600', 19-1125063', '1234', 'abc']

我得到的结果我想要做以下事情:

match_PSargs = re.findall ('ps_args:\s*([-\w:,\s]+)+\s*', my_line)
#match_PSargs = ['com26:57600,    19-1125063, 1234, abc'] 

if match_PSargs: 
        print 'PSargs match_found>', match_PSargs                        
        temp = re.findall('([-\w:]+)', match_PSargs[0])
        #temp = ['com26:57600', '19-1125063', '1234', 'abc']
        print 'temp>', temp

有没有办法只用一个正则表达式来获得所需的结果?

1 个答案:

答案 0 :(得分:1)

使用此模式

([^ ,]+)(?:,|$)

Demo

(               # Capturing Group (1)
  [^ ,]         # Character not in [ ,] Character Class
  +             # (one or more)(greedy)
)               # End of Capturing Group (1)
(?:             # Non Capturing Group
  ,             # ","
  |             # OR
  $             # End of string/line
)               # End of Non Capturing Group