如何捕获多个重复的组? [英] How to capture multiple repeated groups?
问题描述
我需要捕获多个相同模式的组.假设,我有以下字符串:
I need to capture multiple groups of the same pattern. Suppose, I have the following string:
HELLO,THERE,WORLD
我写了以下模式
^(?:([A-Z]+),?)+$
我想要它做的是捕获每个单词,以便第 1 组是:HELLO",第 2 组是THERE";并且第3组是世界".我的正则表达式实际捕获的只是最后一个,即WORLD".
What I want it to do is to capture every single word, so that Group 1 is : "HELLO", Group 2 is "THERE" and Group 3 is "WORLD". What my regex is actually capturing is only the last one, which is "WORLD".
我正在测试我的正则表达式 here 我想将它与 Swift 一起使用(也许 Swift 中有一种方法以某种方式获得中间结果,以便我可以使用它们?)
I'm testing my regular expression here and I want to use it with Swift (maybe there's a way in Swift to get intermediate results somehow, so that I can use them?)
更新:我不想使用split
.我现在只需要知道如何捕获与模式匹配的所有组,而不仅仅是最后一个.
UPDATE: I don't want to use split
. I just need to now how to capture all the groups that match the pattern, not only the last one.
推荐答案
在模式中有一个组,您只能在该组中获得一个确切的结果.如果您的捕获组被模式重复(您在周围的非捕获组上使用了 +
量词),则只会存储与它匹配的最后一个值.
With one group in the pattern, you can only get one exact result in that group. If your capture group gets repeated by the pattern (you used the +
quantifier on the surrounding non-capturing group), only the last value that matches it gets stored.
您必须使用您的语言的正则表达式实现函数来查找模式的所有匹配,然后您必须删除非捕获组的锚点和量词(并且您可以省略非捕获组本身也是如此).
You have to use your language's regex implementation functions to find all matches of a pattern, then you would have to remove the anchors and the quantifier of the non-capturing group (and you could omit the non-capturing group itself as well).
或者,扩展您的正则表达式,让模式包含您想要在结果中获得的每个组一个捕获组:
Alternatively, expand your regex and let the pattern contain one capturing group per group you want to get in the result:
^([A-Z]+),([A-Z]+),([A-Z]+)$
这篇关于如何捕获多个重复的组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!