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

问题描述 投票:1回答:2

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

源字符串可以是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")
javascript regex
2个回答
1
投票

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

您可以使用

specified by op

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

enter image description here


2
投票

假设您不想让Regex democonst 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

匹配一个或多个word boundary。如果要匹配2到3,则1-1

© www.soinside.com 2019 - 2024. All rights reserved.