Javascript中的通配符字符串比较

编程入门 行业动态 更新时间:2024-10-25 23:27:13
本文介绍了Javascript中的通配符字符串比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

let's say I have an array with many Strings Called "birdBlue", "birdRed" and some other animals like "pig1", "pig2).

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

Now I run a for loop that goes through the array and should return all birds. What comparison would make sense here?

动物==鸟* 是我的第一个想法,但不起作用。有没有办法使用运算符*(或者是否有类似的东西使用?

Animals == "bird*" was my first idea but doesnt work. Is there a way to use the operator * (or is there something similar to use?

推荐答案

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

I think you meant something like "*" (star) as a wildcard for example:

  • a * b=>以a开头并以b结尾的所有内容
  • a *=>以a开头的所有内容
  • * b=>以b结尾的所有内容
  • * a *=>其中包含a的所有内容
  • * a * b *=>其中包含a的所有内容,后跟任何内容,后跟b,后跟任何内容
  • "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

或在你的例子中:bird *=>所有开始的东西ith bird

or in your example: "bird*" => everything that starts with bird

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

I had a similar problem and wrote a function with RegExp:

//Short code function matchRuleShort(str, rule) { return new RegExp("^" + rule.split("*").join(".*") + "$").test(str); } //Explanation code function matchRuleExpl(str, rule) { // "." => Find a single character, except newline or line terminator // ".*" => Matches any string that contains zero or more characters rule = rule.split("*").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" );

如果你想阅读有关使用函数的更多信息:

If you want to read more about the used functions:

  • RegExp^,。,*,$
  • string split(*)
  • 数组连接(。*)
  • new RegExp(pattern [,flags])
  • RegExpObject.test(string)
  • RegExp "^, ., *, $"
  • string split("*")
  • array join(".*")
  • new RegExp(pattern[, flags])
  • RegExpObject.test(string)

更多推荐

Javascript中的通配符字符串比较

本文发布于:2023-10-24 14:56:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524238.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:通配符   字符串   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!