gpt4 book ai didi

javascript - 如何使用 Javascript 正则表达式匹配乱序字符串

转载 作者:行者123 更新时间:2023-11-30 13:21:33 26 4
gpt4 key购买 nike

我用 javascript 编写了一个实时过滤器,它从一个字段中获取一个值并隐藏表中不匹配的行。

我为此使用的 RegEx 非常简单:/inputValue/i

虽然这很有效,但它只匹配有序的字符。例如:

inputValue = test
string to match = this is a test sentence

这个例子会匹配,但如果我尝试:

inputValue = this sentence
string to match = this is a test sentence

这不会匹配,因为输入值乱序。

我将如何编写一个有序但可以跳过单词的正则表达式?

这是我目前使用的循环:

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

var comparisonString = liveFilterDataArray[i],
comparisonString = comparisonString.replace(/['";:,.\/?\\-]/g, '');

RE = eval("/" + liveFilterValue + "/i");

if (comparisonString.match(RE)) {
rowsToShow.push(currentRow);
}
if(currentRow < liveFilterGridRows.length - 1) {
currentRow++;
} else {
currentRow = 0;
}
}

非常感谢您的宝贵时间。

克里斯

最佳答案

推荐使用RegExp而不是评估。

DEMO

var words = liveFilterValue.split(" ");
var searchArg = (words.length==1)?words:words.join(".*")+'|'+words.reverse().join(".*")
var RE = new RegExp(searchArg,"i");

它将创建this.*sentence|sentence.*this/i

删除 +'|'+words.reverse().join(".*") 如果您只想找到 this.....sentence 和不是 sentence....this

关于javascript - 如何使用 Javascript 正则表达式匹配乱序字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10103214/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com