我想使用正则表达式在多个位置验证字符
源字符串可以是6-4,4-6,6-4
想在下面验证
the char at position 0 should be [1-7]
the char at position 1 should be [-]
the char at position 2 should be [1-7]
the char at position 3 should be [,]
the char at position 4 should be [1-7]
the char at position 5 should be [-]
the char at position 6 should be [1-7]
the char at position 7 should be [,]
the char at position 8 should be [1-7]
the char at position 9 should be [-]
the char at position 10 should be [1-7]
如果上面匹配则返回true,否则返回false
让我知道如何增强以下内容以验证javascript正则表达式的多个位置和良好参考
new RegExp("^.{0}[1-7]").test("6-4,4-4,6-4")
假设您不想让Regex demo
或const regex = /^(?:[1-7]-[1-7],){1,2}(?:[1-7]-[1-7])$/;
const strs = ['6-4,4-6,6-4', '6-4,6-4', '9-2', '123-1231', '1232', '123#1221', '1-2', '1-2,1-2,1-2,']
strs.forEach(str => {
console.log(str, ' | ', regex.test(str))
})
通过,我会尝试类似的东西
1-1,
,1-1
^(?:[1-7]-[1-7],?\b)+$
See this demo at Regex101用于量化组的逗号,?
与optional匹配(确保每个之间都有逗号,例如\b
)]匹配一个或多个word boundary。如果要匹配2到3,则1-1
。