问题描述
文本以小写字母开头,只能由小写字母、数字、"-"组成,且不能连续出现两个"-"符号,不能以"-"结尾
相关代码
const regex = /^[a-z][a-z0-9-]*[^-]$/g
现在差一个不能连续出现两个"-"符号条件,如果有性能更高的表达式也请写下,求解~!
文本以小写字母开头,只能由小写字母、数字、"-"组成,且不能连续出现两个"-"符号,不能以"-"结尾
const regex = /^[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;
}
10 回答11.1k 阅读
15 回答8.4k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3k 阅读✓ 已解决
8 回答6.2k 阅读
2 回答2.6k 阅读✓ 已解决
/^(?!.+--)[a-z][a-z0-9-]*[^-]$/g
效率稍微高一点的写法
/^[a-z](?!.*--)[a-z0-9-]*[^-]$/g