我有一个由空格分隔的文本值组成的文本文件:
a: b c d e f g
h: i j k
l:
m: n
我不知道这些值有多少- 对; - 我会有先验的。
我想使用 Python groups在正则表达式中能够引用每个捕获。
GnuATgtRE = re.compile(br'^\r\n(?P<target>.+): (?P<deps>.*)\r\n# Implicit rule search has', re.MULTILINE)
目前,<target>引用分号和 <deps> 左侧的项目在一个字符串中引用右侧的所有内容。
我不知道先验有多少deps每个target会有。
语法 (?P<text>) is used to create a group which can be used to reference a specific captured sub-regex .
例如,对于第 1 行
match_obj.group('target') = a match_obj.group('deps') = b c d e f g
第 2 行:
match_obj.group('target') = h match_obj.group('deps') = i j k
问题
在我执行 match = GnuATgtRE.search(string) 之后, 我希望能够引用每个空格分隔的 dep通过match.group('some_text') .
问题是我不知道是否有办法创建任意数量的未命名组。
对于第 1 行,我希望能够说 match.group('<5>')并获得返回d .
对于第 2 行,match.group('<5')应该返回 `` 因为只有 5 个字母。
请您参考如下方法:
参见 this answer .
Most or all regular expression engines in common use, including in particular those based on the PCRE syntax (like Python's), label their capturing groups according to the numerical index of the opening parenthesis, as the regex is written. So no, you cannot use capturing groups alone to extract an arbitrary, variable number of subsequences from a string.
更好的解决方案是在一行中 x: 之后的所有内容上调用 line.split()。
