将正则表达式从两步简化为一步
Simplifying regular expression from two steps to one step
我有以下字符串:
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
有没有办法只用一个正则表达式就可以得到想要的结果?
使用这个模式
([^ ,]+)(?:,|$)
( # 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
我有以下字符串:
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
有没有办法只用一个正则表达式就可以得到想要的结果?
使用这个模式
([^ ,]+)(?:,|$)
( # 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