【问题标题】:regex for multiple option多个选项的正则表达式
【发布时间】:2013-01-11 15:49:36
【问题描述】:

我需要编写一个正则表达式来与 JS .match() 函数一起使用。目标是检查具有多种选择的字符串。例如,如果 mystr 包含 word1 或 word2 或 word3,我想在下面的代码中返回 true

mystr1 = "this_is_my_test string_containing_word2_where_i_will_perform_search";
mystr2 = "this_is_my_test string_where_i_will_perform_search";
myregex = xxxxxx; // I want help regarding this line so that 
if(mystr1.match(myregex)) return true; //should return true
if(mystr2.match(myregex)) return true; //should NOT return true

有什么帮助吗?

【问题讨论】:

  • 正则表达式将检查 str 是否包含任何选项:word1、word2 或 word3?
  • 是的,这就是我的意图……但所有单词都将以逗号分隔格式保存在字符串中。

标签: javascript regex


【解决方案1】:

所以在你的正则表达式中使用 OR |

myregex = /word1|word2|word3/;

【讨论】:

  • 那么,如果我的话是在一个变量中(逗号分隔),这应该工作吗? s = $var.replace(",","|"); myregex = new RegExp(s,"i");
【解决方案2】:

正则表达式是:/word1|word2|word3/

请注意,尽管您的代码可以正常工作,但您实际上并没有使用您需要的方法。

  • string.match(regex) -> 返回匹配数组。当评估为布尔值时,它会在为空时返回 false(这就是它起作用的原因)。
  • regex.test(string) -> 是你应该使用的。它评估字符串是否与正则表达式匹配并返回truefalse

【讨论】:

    【解决方案3】:

    如果您不使用匹配项,那么我可能倾向于使用 test() 方法并包括 i 标志。

    if( /word1|word2|word3/i.test( mystr1 ) ) return true; //should return true
    if( /word1|word2|word3/i.test( mystr2 ) ) return true; //should NOT return true
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-12
      • 1970-01-01
      相关资源
      最近更新 更多