【问题标题】:Switch Case statement for Regex matching in JavaScript用于 JavaScript 中正则表达式匹配的 Switch Case 语句
【发布时间】:2017-11-14 08:41:35
【问题描述】:

所以我有一堆正则表达式,我尝试使用这个 If 语句查看它们是否与另一个字符串匹配:

if(samplestring.match(regex1)){ 
 console.log("regex1");
} else  if(samplestring.match(regex2)){     
 console.log("regex2");
} else  if(samplestring.match(regex3)){
 console.log("regex3");
}

但是一旦我需要使用更多的正则表达式,这会变得非常难看,所以我想使用这样的 switch case 语句:

switch(samplestring){
case samplestring.match(regex1): console.log("regex1");
case samplestring.match(regex2): console.log("regex2");
case samplestring.match(regex3): console.log("regex3");
}

问题是它不像我在上面的例子中那样工作。 关于它如何工作的任何想法?

【问题讨论】:

  • 我想你跳过了break
  • 匹配后的每个case都会被执行,除非浏览器读取break关键字。
  • 我添加了 break 关键字,但它仍然不起作用

标签: javascript


【解决方案1】:

您需要使用不同的检查,而不是使用String#match,它返回一个数组或null,这在严格比较时不可用,例如switch statement

您可以使用RegExp#test 并与true 核对:

var regex1 = /a/,
    regex2 = /b/,
    regex3 = /c/,
    samplestring = 'b';

switch (true) {
    case regex1.test(samplestring):
        console.log("regex1");
        break;
    case regex2.test(samplestring):
        console.log("regex2");
        break;
    case regex3.test(samplestring):
        console.log("regex3");
        break;
}

【讨论】:

  • 这行得通,但我在某处读到这不是一个非常干净的方法来执行 switch case 语句,这是真的吗?
  • 这是一个干净的模式,除了它按预期工作。
【解决方案2】:
switch (samplestring) {
  case samplestring.match(regex1):
    console.log("regex1");
    break;
  case samplestring.match(regex2):
    console.log("regex2");
    break;
  case samplestring.match(regex3):
    console.log("regex3");
    break;
}

尝试添加break;

【讨论】:

  • 你试过这个吗? 它不起作用!缺少休息不是唯一的问题。
  • switch 与严格比较器一起使用,因此数组永远不会严格等于字符串,或者null 永远不会严格等于字符串。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-28
  • 2011-05-01
  • 1970-01-01
  • 2012-03-26
  • 1970-01-01
相关资源
最近更新 更多