Python 正则表达式中的动态命名组
有没有办法动态更新Python中正则表达式组的名称?
例如,如果文本是:
person 1: name1
person 2: name2
person 3: name3
...
person N: nameN
在事先不知道有多少人的情况下,您如何命名组“person1”、“person2”、“person3”、...和“personN”?
Is there a way to dynamically update the name of regex groups in Python?
For example, if the text is:
person 1: name1
person 2: name2
person 3: name3
...
person N: nameN
How would you name groups 'person1', 'person2', 'person3', ..., and 'personN' without knowing beforehand how many people there are?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,但你可以这样做:
输出:
快速解释:
引用
No, but you can do something like this:
output:
A quick explanation:
References
命名捕获组和编号组(\1、\2 等)不能是动态的,但您可以使用 findall 实现相同的效果:
named capture groups and numbered groups (\1, \2, etc.) cannot be dynamic, but you can achieve the same thing with findall:
从您接受的答案来看,不需要正则
表达式输出
judging from your accepted answer, there's no need for regex
output
Python 中的正则表达式(我非常确定这对于一般的正则表达式来说是正确的)不允许任意数量的匹配。您可以捕获整个重复匹配(通过在重复组周围放置捕获括号)或捕获一系列匹配中的最后一个匹配(通过重复捕获组)。这与这些捕获组是命名的还是编号的无关。
您需要通过迭代字符串中的所有匹配项以编程方式执行此操作,例如
Regexes in Python (and I'm pretty certain that that's true for regexes in general) don't allow for an arbitrary number of matches. You can either capture a repeated match in its entirety (by placing capturing parentheses around a repeated group) or capture the last match in a series of matches (by repeating a capturing group). This is independent of whether these are named or numbered capturing groups.
You need to do this programmatically by iterating over all matches in a string, like