我想验证并分析这个字符串(用引号括起来):
string = "start: c12354, c3456, 34526; other stuff that I don't care about"
//Note that some codes begin with 'c'
我想验证字符串是否以“start”开头,以“;”结尾 之后,我想让regex解析字符串。我尝试了以下python重新编码:
regx = r"start: (c?[0-9]+,?)+;"
reg = re.compile(regx)
matched = reg.search(string)
print ' matched.groups()', matched.groups()
我尝试过不同的变体,但我可以得到第一个或最后一个代码,但不能得到这三个代码的列表。
或者我应该放弃使用regex?
编辑:更新以反映我忽略的部分问题空间,并修复了字符串差异。 谢谢你的建议-在这么短的时间内。
您可以使用标准的字符串工具,这些工具通常更具可读性。
s = "start: c12354, c3456, 34526;"
s.startswith("start:") # returns a boolean if it starts with this string
s.endswith(";") # returns a boolean if it ends with this string
s[6:-1].split(', ') # will give you a list of tokens separated by the string ", "
在Python中,这在一个正则表达式中是不可能的:组的每个捕获都会覆盖同一组的最后一个捕获(在.NET中,这实际上是可能的,因为引擎区分了捕获和组)。
最简单的解决方案是先提取} 。
start:
和;
之间的部分,然后使用正则表达式返回所有的匹配项,而不仅仅是单个匹配项,使用^{这可以用Pyparsing这样的工具来完成(相当优雅):
比正则表达式更干净,返回代码列表(不需要
string.split
),并忽略行中的任何额外字符,就像您的示例一样。相关问题 更多 >
编程相关推荐