用于重复字符串的python正则表达式

2024-03-28 22:21:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我想验证并分析这个字符串(用引号括起来):

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?

编辑:更新以反映我忽略的部分问题空间,并修复了字符串差异。 谢谢你的建议-在这么短的时间内。


Tags: 字符串代码stringthatregstart引号regex
3条回答

您可以使用标准的字符串工具,这些工具通常更具可读性。

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这样的工具来完成(相当优雅):

from pyparsing import Group, Literal, Optional, Word
import string

code = Group(Optional(Literal("c"), default='') + Word(string.digits) + Optional(Literal(","), default=''))
parser = Literal("start:") + OneOrMore(code) + Literal(";")
# Read lines from file:
with open('lines.txt', 'r') as f:
    for line in f:
        try:
            result = parser.parseString(line)
            codes = [c[1] for c in result[1:-1]]
            # Do something with teh codez...
        except ParseException exc:
            # Oh noes: string doesn't match!
            continue

比正则表达式更干净,返回代码列表(不需要string.split),并忽略行中的任何额外字符,就像您的示例一样。

相关问题 更多 >