Javascript-正则表达式以验证特定位置的字符

时间:2019-09-29 16:09:44

标签: javascript regex

我想使用正则表达式在多个位置验证字符

源字符串可以是6-4,4-6,6-4

想在下面进行验证

  1. the char at position 0 should be [1-7]

  2. the char at position 1 should be [-]

  3. the char at position 2 should be [1-7]

  4. the char at position 3 should be [,]

  5. the char at position 4 should be [1-7]

  6. the char at position 5 should be [-]

  7. the char at position 6 should be [1-7]

  8. the char at position 7 should be [,]

  9. the char at position 8 should be [1-7]

  10. the char at position 9 should be [-]

  11. the char at position 10 should be [1-7]

如果上面匹配则返回true,否则返回false

让我知道如何增强以下内容以验证javascript正则表达式的多个位置和良好参考

new RegExp("^.{0}[1-7]").test("6-4,4-4,6-4")

2 个答案:

答案 0 :(得分:2)

假设您不想让1-1,,1-1通过,我会尝试类似的方法

^(?:[1-7]-[1-7],?\b)+$

See this demo at Regex101

匹配一个或多个1-1。如果要匹配2到3,请use {2,3} instead of of + at end

答案 1 :(得分:1)

  

源可以是7个字符或11个字符,并且不会包含,   结束。 specified by op

您可以使用

^(?:[1-7]-[1-7],){1,2}(?:[1-7]-[1-7])$

enter image description here

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))
})