Javascript Javascript中的通配符字符串比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26246601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Wildcard string comparison in Javascript
提问by xqz313
Let's say I have an array with many Strings Called "birdBlue", "birdRed"and some other animals like "pig1", "pig2").
假设我有一个包含许多 Strings Called 的数组"birdBlue","birdRed"以及一些其他的动物,如"pig1", "pig2")。
Now I run a for loop that goes through the array and should return all birds. What comparison would make sense here?
现在我运行一个遍历数组的 for 循环,应该返回所有的鸟。什么比较在这里有意义?
Animals == "bird*"was my first idea but doesn't work. Is there a way to use the operator * (or is there something similar to use?
Animals == "bird*"是我的第一个想法,但不起作用。有没有办法使用运算符 * (或者是否有类似的用法?
回答by Spenhouet
I think you meant something like "*" (star) as a wildcard for example:
我认为您的意思是“*”(星号)作为通配符,例如:
- "a*b" => everything that starts with "a" and ends with "b"
- "a*" => everything that starts with "a"
- "*b" => everything that ends with "b"
- "*a*" => everything that has an "a" in it
- "*a*b*"=> everything that has an "a" in it, followed by anything, followed by a "b", followed by anything
- "a*b" => 以 "a" 开头并以 "b" 结尾的所有内容
- "a*" => 以 "a" 开头的所有内容
- "*b" => 以 "b" 结尾的所有内容
- "*a*" => 包含 "a" 的所有内容
- "*a*b*"=> 包含“a”的所有内容,然后是任何内容,然后是“b”,然后是任何内容
or in your example: "bird*" => everything that starts with bird
或在您的示例中:“bird*” => 以bird 开头的所有内容
I had a similar problem and wrote a function with RegExp:
我遇到了类似的问题,并用 RegExp 编写了一个函数:
//Short code
function matchRuleShort(str, rule) {
var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\])/g, "\");
return new RegExp("^" + rule.split("*").map(escapeRegex).join(".*") + "$").test(str);
}
//Explanation code
function matchRuleExpl(str, rule) {
// for this solution to work on any string, no matter what characters it has
var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\])/g, "\");
// "." => Find a single character, except newline or line terminator
// ".*" => Matches any string that contains zero or more characters
rule = rule.split("*").map(escapeRegex).join(".*");
// "^" => Matches any string with the following at the beginning of it
// "$" => Matches any string with that in front at the end of it
rule = "^" + rule + "$"
//Create a regular expression object for matching string
var regex = new RegExp(rule);
//Returns true if it finds a match, otherwise it returns false
return regex.test(str);
}
//Examples
alert(
"1. " + matchRuleShort("bird123", "bird*") + "\n" +
"2. " + matchRuleShort("123bird", "*bird") + "\n" +
"3. " + matchRuleShort("123bird123", "*bird*") + "\n" +
"4. " + matchRuleShort("bird123bird", "bird*bird") + "\n" +
"5. " + matchRuleShort("123bird123bird123", "*bird*bird*") + "\n" +
"6. " + matchRuleShort("s[pe]c 3 re$ex 6 cha^rs", "s[pe]c*re$ex*cha^rs") + "\n" +
"7. " + matchRuleShort("should not match", "should noo*oot match") + "\n"
);
If you want to read more about the used functions:
如果您想阅读有关所用函数的更多信息:
回答by Davsket
You should use RegExp (they are awesome) an easy solution is:
您应该使用 RegExp(它们很棒)一个简单的解决方案是:
if( /^bird/.test(animals[i]) ){
// a bird :D
}
回答by Cody Reichert
You could use Javascript's substringmethod. For example:
您可以使用 Javascript 的substring方法。例如:
var list = ["bird1", "bird2", "pig1"]
for (var i = 0; i < list.length; i++) {
if (list[i].substring(0,4) == "bird") {
console.log(list[i]);
}
}
Which outputs:
哪些输出:
bird1
bird2
Basically, you're checking each item in the array to see if the first four letters are 'bird'. This does assume that 'bird' will always be at the front of the string.
基本上,您正在检查数组中的每个项目以查看前四个字母是否为“鸟”。这确实假设 'bird' 将始终位于字符串的前面。
So let's say your getting a pathname from a URL :
因此,假设您从 URL 获取路径名:
Let's say your at bird1?=letsfly - you could use this code to check the URL:
假设您在 Bird1?=letsfly - 您可以使用此代码检查 URL:
var listOfUrls = [
"bird1?=letsfly",
"bird",
"pigs?=dontfly",
]
for (var i = 0; i < list.length; i++) {
if (listOfUrls[i].substring(0,4) === 'bird') {
// do something
}
}
The above would match the first to URL's, but not the third (not the pig). You could easily swap out url.substring(0,4)with a regex, or even another javascript method like .contains()
以上将匹配第一个到 URL,但不匹配第三个(不是猪)。您可以轻松地url.substring(0,4)使用正则表达式或其他 javascript 方法(如 .contains())进行替换
Using the .contains()method might be a little more secure. You won't need to know which part of the URL 'bird' is at. For instance:
使用该.contains()方法可能更安全一些。您不需要知道 URL 'bird' 的哪一部分。例如:
var url = 'www.example.com/bird?=fly'
if (url.contains('bird')) {
// this is true
// do something
}
回答by Kamil Kie?czewski
This function convert wildcard to regexp and make test (it supports .and *wildcharts)
此函数将通配符转换为正则表达式并进行测试(它支持.和通配符*)
function wildTest(wildcard, str) {
let w = wildcard.replace(/[.+^${}()|[\]\]/g, '\$&'); // regexp escape
const re = new RegExp(`^${w.replace(/\*/g,'.*').replace(/\?/g,'.')}$`,'i');
return re.test(str); // remove last 'i' above to have case sensitive
}
function wildTest(wildcard, str) {
let w = wildcard.replace(/[.+^${}()|[\]\]/g, '\$&'); // regexp escape
const re = new RegExp(`^${w.replace(/\*/g,'.*').replace(/\?/g,'.')}$`,'i');
return re.test(str); // remove last 'i' above to have case sensitive
}
// Example usage
let arr = ["birdBlue", "birdRed", "pig1z", "pig2z", "elephantBlua" ];
let resultA = arr.filter( x => wildTest('biRd*', x) );
let resultB = arr.filter( x => wildTest('p?g?z', x) );
let resultC = arr.filter( x => wildTest('*Blu?', x) );
console.log('biRd*',resultA);
console.log('p?g?z',resultB);
console.log('*Blu?',resultC);
回答by James Hay
var searchArray = function(arr, str){
// If there are no items in the array, return an empty array
if(typeof arr === 'undefined' || arr.length === 0) return [];
// If the string is empty return all items in the array
if(typeof str === 'undefined' || str.length === 0) return arr;
// Create a new array to hold the results.
var res = [];
// Check where the start (*) is in the string
var starIndex = str.indexOf('*');
// If the star is the first character...
if(starIndex === 0) {
// Get the string without the star.
str = str.substr(1);
for(var i = 0; i < arr.length; i++) {
// Check if each item contains an indexOf function, if it doesn't it's not a (standard) string.
// It doesn't necessarily mean it IS a string either.
if(!arr[i].indexOf) continue;
// Check if the string is at the end of each item.
if(arr[i].indexOf(str) === arr[i].length - str.length) {
// If it is, add the item to the results.
res.push(arr[i]);
}
}
}
// Otherwise, if the star is the last character
else if(starIndex === str.length - 1) {
// Get the string without the star.
str = str.substr(0, str.length - 1);
for(var i = 0; i < arr.length; i++){
// Check indexOf function
if(!arr[i].indexOf) continue;
// Check if the string is at the beginning of each item
if(arr[i].indexOf(str) === 0) {
// If it is, add the item to the results.
res.push(arr[i]);
}
}
}
// In any other case...
else {
for(var i = 0; i < arr.length; i++){
// Check indexOf function
if(!arr[i].indexOf) continue;
// Check if the string is anywhere in each item
if(arr[i].indexOf(str) !== -1) {
// If it is, add the item to the results
res.push(arr[i]);
}
}
}
// Return the results as a new array.
return res;
}
var birds = ['bird1','somebird','bird5','bird-big','abird-song'];
var res = searchArray(birds, 'bird*');
// Results: bird1, bird5, bird-big
var res = searchArray(birds, '*bird');
// Results: somebird
var res = searchArray(birds, 'bird');
// Results: bird1, somebird, bird5, bird-big, abird-song
There is an long list of caveats to a method like this, and a long list of 'what ifs' that are not taken into account, some of which are mentioned in other answers. But for a simple use of star syntax this may be a good starting point.
像这样的方法有一长串警告,还有一长串没有考虑的“假设”,其中一些在其他答案中提到。但是对于星形语法的简单使用,这可能是一个很好的起点。
回答by lenden
if(mas[i].indexOf("bird") == 0)
//there is bird
You.can read about indexOf here: http://www.w3schools.com/jsref/jsref_indexof.asp
您可以在此处阅读有关 indexOf 的信息:http: //www.w3schools.com/jsref/jsref_indexof.asp
回答by user11776319
Instead Animals == "bird*"Animals = "bird*"should work.
相反Animals == "bird*"Animals = "bird*"应该工作。

