Javascript中的通配符字符串比较

xqz*_*313 42 javascript string comparison

假设我有一个包含许多字符串的数组,名为"birdBlue","birdRed"和其他一些动物,如"pig1","pig2".

现在我运行一个遍历数组的for循环,并且应该返回所有的鸟.什么比较在这里有意义?

"birdBlue"是我的第一个想法但不起作用.有没有办法使用运营商*(或有类似的使用?

Spe*_*pen 86

我认为你的意思是"*"(星号)作为通配符,例如:

  • "a*b"=>以"a"开头并以"b"结尾的所有内容
  • "a*"=>以"a"开头的所有内容
  • "*b"=>以"b"结尾的一切
  • "*a*"=>其中包含"a"的所有内容
  • "*a*b*"=>其中包含"a"的所有内容,后跟任何内容,后跟"b",后跟任何内容

或者在你的例子中:"bird*"=>以鸟为开头的一切

我遇到了类似的问题并使用RegExp编写了一个函数:

//Short code
function matchRuleShort(str, rule) {
  var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
  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, "\\$1");

  // "."  => 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"
);
Run Code Online (Sandbox Code Playgroud)


如果您想了解有关使用函数的更多信息:

  • @Spen,你的答案让我大部分都在那里,但是如果你使用网址,就有可能出现误报.例如`matchRuleShort("https://evil.com","https://*.il.com)`评估为true!为了防止这种情况,我必须使用转义的等价物来转义所有非*字符."return new RegExp("^"+ rule.replace(/ [.?+ ^ $ [\] \\(){} | - ]/g,"\\ $&");. split("*").join( ".*")+"$").test(str);`正则表达式借用http://stackoverflow.com/a/2593661/238638 (4认同)

Dav*_*ket 10

您应该使用RegExp(它们很棒)一个简单的解决方案是:

if( /^bird/.test(animals[i]) ){
    // a bird :D
}
Run Code Online (Sandbox Code Playgroud)

  • 语义上更好的选择可能是`/ ^bird /.test(...)`. (2认同)

Cod*_*ert 7

您可以使用 Javascript 的子字符串方法。例如:

var list = ["bird1", "bird2", "pig1"]

for (var i = 0; i < list.length; i++) {
  if (list[i].substring(0,4) == "bird") {
   console.log(list[i]);
  }
}
Run Code Online (Sandbox Code Playgroud)

哪个输出:

bird1
bird2
Run Code Online (Sandbox Code Playgroud)

基本上,您要检查数组中的每个项目,看看前四个字母是否是“bird”。这确实假设“bird”始终位于字符串的前面。


假设您从 URL 获取路径名:

假设您的 at 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
  }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码将匹配第一个 URL,但不匹配第三个(不是猪)。url.substring(0,4)您可以轻松地使用正则表达式,甚至其他 javascript 方法(例如 .contains())进行替换


使用该.contains()方法可能会更安全一些。您不需要知道 URL“bird”位于 URL 的哪一部分。例如:

var url = 'www.example.com/bird?=fly'

if (url.contains('bird')) {
  // this is true
  // do something
}
Run Code Online (Sandbox Code Playgroud)


Kam*_*ski 6

此函数将通配符转换为正则表达式并进行测试(它支持.和通配符*

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
}
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)


len*_*den -3

if(mas[i].indexOf("bird") == 0)
    //there is bird
Run Code Online (Sandbox Code Playgroud)

您可以在这里阅读有关indexOf的信息:http ://www.w3schools.com/jsref/jsref_indexof.asp

  • 请注意,这对于不以“bird”开头的长字符串有很大的开销。使用 [`startsWith` 可能是更好的解决方案](http://stackoverflow.com/q/646628/1048572) (3认同)