简体   繁体   English

在正则表达式中使用单个组匹配重复模式

[英]Match repeating pattern using single group in regex

Using the JS regex object, is it possible to match a repeating pattern using a single, or few groups? 使用JS正则表达式对象,是否可以使用一个或几个组来匹配重复模式?

For instance, taking the following as input: 例如,将以下内容作为输入:

#222<abc#321cba#123>#111

Would it be possible to match both "#321" and "#123" (but not #222 or #111, as they're outside the /<.*?>/ group) using a regex similar to: 是否可以使用类似于以下内容的正则表达式来匹配“#321”和“#123”(但不匹配#222或#111,因为它们在/<.*?>/组之外):

/<.*?(?:(#[0-9]+).*?)>/

(which currently only matches the first instance), when the number of matches in the input is unknown? (当前仅与第一个实例匹配),如果输入中的匹配数量未知?

You'd have to loop over the inner pattern. 您必须遍历内部模式。 First use /<(.*?)>/ to extract it: 首先使用/<(.*?)>/提取它:

var outerRegex = /<(.*?)>/;
var match = outerRegex.exec(input);
var innerPattern = match[1];

Next, iterate over the result: 接下来,遍历结果:

var innerRegex = /#\d+/g;
while (match = innerRegex.exec(innerPattern))
{
    var result = match[0];
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM