我的正则表达式分组为什么不能正确分组?

时间:2019-06-18 07:27:38

标签: python regex

文件中的一行示例:“ CIS 14A Visual Basic .NET编程I x x x x”

我试图将文件中的行分为三组:group(0)应该是课程编号(14A),group(1)应该是主题(Visual Basic .NET Programming I),而group( 2)应该是课程可用的四分之一。但是,当我测试代码时,group(0)与整行匹配,group(1)是课程编号,group(2)为空...,而group (3)是主题和可用季度的组合。我找不到问题所在,因为每组括号都创建了一个组,但是所有组的顺序都不正确,并且出于某种原因,我未包含在任何括号中的“ CIS”被包含在group(0)中。我是regex的新手,所以非常感谢您提供有关如何修复代码的建议。

    with open(filename) as infile:
        for line in infile:
            self._match = (re.search('^CIS\s(\d*\w*)(\w*)\s?[^x]*(.*)$', line, re.I))
            self._numb = self._match.group(0).strip()
            self._name = self._match.group(1).strip()
            self._quarter=self._match.group(2).strip().split('x')

1 个答案:

答案 0 :(得分:2)

请注意,.group()总是与捕获组+ 1一样多,因为第零组是为整个比赛保留的。

您可能使用的正则表达式是

^CIS\s+([0-9A-Z]+)\s(.*?)\s(x\s.*)

请参见regex demo

请参阅Python代码段:

with open(filename, 'r') as infile:
    for line in infile:
        self._match = re.search(r'^CIS\s+([0-9A-Z]+)\s(.*?)\s(x\s.*)', line, re.I)
        if self._match:
            self._numb = self._match.group(1).strip()
            self._name = self._match.group(2).strip()
            self._quarter=self._match.group(3).strip().split('x')

正则表达式详细信息

  • ^-字符串的开头
  • CIS-文字子字符串
  • \s+-超过1个空格
  • ([0-9A-Z]+)-第1组:一个或多个数字或大写字母
  • \s-空格
  • (.*?)-第2组:除换行符以外的任何0个或多个字符,应尽可能少
  • \s-空格
  • (x\s.*)-第3组:x,空格和除换行符以外的0个或更多字符。

还要检查regex graph

enter image description here

enter image description here