是否可以链接jQuery Regexp匹配项? [英] Is it possible to chain jQuery Regexp matches?

查看:63
本文介绍了是否可以链接jQuery Regexp匹配项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我很好奇是否有一种方法可以链接正则表达式.只是想优化我的代码.我想找到一个表达式,然后从结果中找到另一个.

So I'm just curious if there was a way to chain regexp. Just looking to optimize my code a little. I want to find an expression, then find another one from the results.

工作代码:

match = $('body').html().match(/(\[~\{ .*? \}~\])/g);
console.log(match[0]);

findText = match[0].match(/\w+/);
console.log(findText);

我尝试过的事情:

match = $('body').html().match(/(\[~\{ .*? \}~\])(\w+)/g);
console.log(match[0]);

产生了错误

match = $('body').html().match(/(\[~\{ .*? \}~\])|(\w+)/g);
console.log(match[0]);

找到表达式1,然后在表达式1之外找到表达式2.

Found Expression 1 and then Found Expression 2 outside of expression 1.

我的HTML:

[~{ header }~]

<p>This is the home page</p>

[~{ footer }~]

推荐答案

我只是对[~{ ... }~]结构中的单词使用了捕获组.

I just used a capturing group for the word inside the [~{ ... }~] structure.

\[~\{ (\w+) \}~\]

唯一的区别是我匹配了(\w+)而不是.*?.我也删除了整个表达式周围的捕获组((...)),因为这不是必需的.

The only difference is I matched (\w+) instead of .*?. I also removed the capture group ((...)) that was around the whole expression, since it wasn't necessary.

Regex101

现在使用Javascript访问多个捕获组有点困难,但是我使用了此答案中的一些示例代码(感谢Mathias Bynens):

Now it is a little difficult to access multiple capture groups in Javascript, but I used some example code from this answer (thanks Mathias Bynens):

function getMatches(string, regex) {
    var matches = [];
    var match;
    while (match = regex.exec(string)) {
        matches.push(match);
    }
    return matches;
}

var myString = $('body').html();
var myRegEx = /\[~\{ (\w+) \}~\]/g;

var matches = getMatches(myString, myRegEx);
console.log(matches[0]);

输出:

Array[2]
  0: "[~{ header }~]"    // The whole match
  1: "header"            // The captured group

JSFiddle

所以您的最终代码可能看起来像这样(这是伪代码):

So your final code could look something like this (this is pseudo-code):

matches; // this is set from previous code block

for(var i = 0; i < matches.length; i++) {
    var needsToBeReplaced = matches[i][0];
    var template = getTemplate(matches[i][1]);
}

这篇关于是否可以链接jQuery Regexp匹配项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆