求一个正则的连续两次符号的匹配

问题描述

文本以小写字母开头,只能由小写字母、数字、"-"组成,且不能连续出现两个"-"符号,不能以"-"结尾

相关代码

const regex = /^[a-z][a-z0-9-]*[^-]$/g

现在差一个不能连续出现两个"-"符号条件,如果有性能更高的表达式也请写下,求解~!

阅读 4.4k
3 个回答

/^(?!.+--)[a-z][a-z0-9-]*[^-]$/g

效率稍微高一点的写法
/^[a-z](?!.*--)[a-z0-9-]*[^-]$/g

var exp=/^[a-z](?:[a-z0-9]|-(?!-))*\b(?!-)$/; //下面连续测试就没有加 g

//match
console.log(exp.exec("a"))
console.log(exp.exec("a12b"))
console.log(exp.exec("a-1-2-3-b"))

//not match
console.log(exp.exec("123"))
console.log(exp.exec("123abc"))
console.log(exp.exec("a-"))
console.log(exp.exec("a--1"))
console.log(exp.exec("a-1--2"))
console.log(exp.exec("a-1-2-"))

我觉得这样效率也不差

function exec(str) {
  if (typeof str === 'string') {
    if (str.length === 1) {
      return str !== '-';
    } else {
      if (/^[a-z][a-z0-9-]*[^-]$/g.test(str)) {
        return !str.includes('--');
      }
      return false;
    }
  }
  return false;
}

如果想让人看不懂,可以简写

function exec(str) {
  if (typeof str === 'string') {
    return str.length === 1 ? str !== '-' : /^[a-z][a-z0-9-]*[^-]$/g.test(str) && !str.includes('--');
  }
  return false;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题