我需要验证填字线索的枚举(括号中的数字)。例如,“大星(3,5)”-枚举是3,5。
我正在为所需的正则表达式而奋斗。规则应如下:
一些有效的例子..。
一些无效的例子..。
希望你能明白。任何帮助都将不胜感激。
发布于 2021-06-20 21:58:07
正则表达式非常强大,但有时却很难写出,特别是如果您不经常使用它们。这就是为什么我经常使用本站提供帮助的原因。
在评论中发言后,一个逻辑错误变得很明显: regexp不会与0匹配任何东西,即使它没有以它开始。如果没有-,它也不会匹配数字,就像10一样。
现在,我想出了([1-9]([0-9]+)?(((\-|\,)[1-9]([0-9]+)?)+)?),但是还有另一个问题:
10-5-40将按预期匹配3-2在03-2和3 and 2在03-02也将是匹配的。因此,除了RegExp之外,我还包含了一些JS逻辑。希望现在它能如愿以偿。
let Regexp1 = /([1-9]([0-9]+)?(((\-|\,)[1-9]([0-9]+)?)+)?)/;
let Regexp2 = /([1-9]([0-9]+)?(((\-|\,)[1-9]([0-9]+)?)+))/;
function test(t) {
match1 = (t.match(Regexp1) != null);
match2 = (t.match(Regexp2) != null);
let matches = false;
if(match1 && match2) {
matches = true;
} else if(match1 && !match2) {
if(t.match(Regexp1)[0].length == t.length) {
matches = true;
} else {
matches = false;
}
}
if(t.match(Regexp1)[0].length != t.length) {
matches = false;
}
console.log(matches);
return matches;
}
test("10-5"); // true
test("03-4"); // false
test("0-5"); // false
test("1,05"); // false
test("1--5"); // false
test("10"); // true
test("10-05"); // false
https://stackoverflow.com/questions/68060298
复制相似问题