【问题标题】:Javascript Regex - match int after string in for loopJavascript Regex - 在for循环中匹配字符串后的int
【发布时间】:2018-10-23 12:49:54
【问题描述】:

我正在尝试捕获与字符串 txt 中的关键字相关的计数。所有关键字都提前加载到数组中。

此代码在 jquery/javascript 中。我不能对字符串关键字进行硬编码,这就是它们存储在数组中的原因。请帮助我在循环中的关键字变量之前和/或之后找到代替“Reg Expression”的内容。

html br 可用于在循环的该迭代中结束该正则表达式匹配。

试图以 keywordCount = "2, 5, 11" 结尾

//String I need to search through
var txt = "Edit Req'd2<br>Errors5<br>Pndg App11<br>";

//array of keywords I can use to find associated counts to keywords
var keyword = ["Edit Req'd", "Errors", "Pndg App"];

//empty string declared before loop
var keywordCount = '';

for (i = 0; i < keyword.length; i++) {

    // takes the comma off end of first entry in array
    // might not be needed or another method might be better?
    keyword[i] = $.trim(keyword[i]);

    //regex expression generated using keyword and unknown expression 
    var regexmatch = RegExp("Reg Expression" + keyword + "Reg Expression")

    //use regex expression to generate string containing counts
    keywordCount += (txt.match(regexmatch)) + ",";
}

【问题讨论】:

标签: javascript jquery regex


【解决方案1】:

这是一个可以帮助您实现所需输出的示例。

//String I need to search through
var txt = "Edit Req'd2<br>Errors5<br>Pndg App11<br>";

//array of keywords I can use to find associated counts to keywords
var keyword = ["Edit Req'd", "Errors", "Pndg App"];

//empty string declared before loop
var keywordCount = '';
var i = 0;
var keywordCount = "";
var splittedValue = "";
while (i < keyword.length) {
    if (txt.indexOf(keyword[i]/i)) {
        splittedValue = txt.split(keyword[i]);
        if (keywordCount === "") {
            keywordCount = splittedValue[1].split("<br>")[0];
        } else {
            keywordCount += ", " + splittedValue[1].split("<br>")[0];
        }
    }
    i += 1;
}
console.log(keywordCount);

【讨论】:

    【解决方案2】:

    我会使用数字/数字范围来匹配数字([0-9];这是非常基本的正则表达式),并使用组来匹配任何关键字:

    • 任意位数:[0-9]+
    • 您的任何关键字:(something|somethingelse|other)

    您也可以使用捕获组让match() 分别返回它们:

    var keyword = ["Edit Req'd", "Errors", "Pndg App"];
    var regexmatch = RegExp('(\b' + keyword.join('|') + ')([0-9]+)', 'g')
    

    (请注意,我们使用单词边界 \b 来确保关键字不是较长单词的一部分,并且全局的 'g' 标志表示我们想要多个结果)

    现在,match() 只会匹配一个结果,并且我们希望匹配每个关键字,所以我们将使用 exec() 代替:

    var txt = "Edit Req'd2<br>Errors5<br>Pndg App11<br>";
    var keyword = ["Edit Req'd", "Errors", "Pndg App"];
    var regex = RegExp('(\b' + keyword.join('|') + ')([0-9]+)', 'g')
    
    var match = regex.exec( txt ); // ...find the first match
    var numbers = [];
    
    while ( match !== null ) {
      numbers.push( match[ 2 ]); // #0 of exec() its return-value is the result as a whole: "Edit Req'd2"
                                 // #1 is the value of the first capture-group: "Edit Req'd"
                                 // #2 is the value of the second capture-group: "2"
    
      match = regex.exec( txt ); // ...find the next match
    }
    
    console.log("the numbers are:", numbers);

    最后,请注意正则表达式可能看起来很酷,它们是not always the fastest(性能方面)。如果性能很重要,您可以使用(例如)indexOf()


    从您的问题来看,您似乎可以稍微复习一下您对正则表达式的了解。周围有很多文章(只需搜索“正则表达式基础知识”“regex 101”)——比如这个: https://medium.com/factory-mind/regex-tutorial-a-simple-cheatsheet-by-examples-649dc1c3f285*

    【讨论】:

    • JavaScript 正则表达式不支持向后看。
    • 谢谢,使用在线正则表达式测试器和开发工具控制台进行了测试,但显然太懒了;并非所有浏览器都支持它们。将答案更改为无需后顾之忧。
    猜你喜欢
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 2021-10-24
    • 2017-02-01
    • 1970-01-01
    相关资源
    最近更新 更多