简体   繁体   English

javascript中的正则表达式匹配错误

[英]Regex match error in javascript

I have seen Return positions of a regex match() in Javascript? 我已经在Java中看到了正则表达式match()的返回位置吗? but not sure how to implement it in my case 但不确定如何在我的情况下实施

I have an array item_array and I want to filter all items containing text val 我有一个数组item_array ,我想过滤所有包含文本val项目

This is the code I'm using : 这是我正在使用的代码:

I have made a function matchdata to filter the results 我做了一个函数matchdata来过滤结果

var matchdata = function(text_to_match, item_array) {
    var reg = new RegExp(text_to_match.split('').join('\\w*').replace(/\W/, ""), 'i');
    return item_array.filter(function(item) {
        if (item.match(reg)) {
            return item;
        }
    });
};

And I'm using it like 我正在使用它

var matching_items = matchdata(val, item_array);

Now I have 2 questions : 现在我有两个问题:

  1. When val ( item to find in array ) contains more than one \\ , it starts giving this error in console : val (要在数组中找到的项)包含多个\\ ,它将开始在控制台中出现以下错误:

Uncaught SyntaxError: Invalid regular expression: /\\w*\\w*/: \\ at end of pattern(…) 未捕获的SyntaxError:无效的正则表达式:/ \\ w * \\ w * /:\\(位于模式末尾(...))

Why is this happening ? 为什么会这样呢? and is there any way to rectify this ? 有什么办法纠正这个问题吗?

  1. Is there any way the filter function can return the matched item index along with the matched item ( assuming there can be duplicate entries in the array ) filter函数是否可以通过任何方式将匹配项索引匹配项一起返回(假设数组中可以有重复的条目)

This function is your 'regex idea' coded in a for-loop: 此函数是您在循环中编码的“正则表达式主意”

function isSubstring (input, text) {
    input = input.toLowerCase();
    text = text.toLowerCase();
    var found = 0;
    var nextChar = input.charAt(found);
    for (var i=0, l=text.length; i<l; i++) {
        if (text.charAt(i) === nextChar) {
            found++;
            if (found === input.length)
                return true;
            nextChar = input.charAt(found);
        }
    }
};

Basically, it will look for a substring with zero or more characters between each matched letter: 基本上,它将在每个匹配字母之间寻找具有零个或多个字符的子字符串:

isSubstring('BZL', 'Brazil');  // true
//                  ^  ^ ^

Then, your code will look like: 然后,您的代码将如下所示:

var matchdata = function(text_to_match, item_array) {
    var result = item_array.map(function(item, index) {
        if (isSubstring(text_to_match, item)) {
            return [item, index];
        }
        return 0;
    });
    return result.filter(isNaN);
};

The result will be a matrix: result将是一个矩阵:

matchdata('bzl', ['BraZiL', 'LiZarB', 'BraZiL']);
// [ ['brazil', 0], ['brazil', 2] ]

Hope it helps :) 希望能帮助到你 :)

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

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