代码之家  ›  专栏  ›  技术社区  ›  upog

javascript-regex来验证特定位置的字符

  •  0
  • upog  · 技术社区  · 5 年前

    我想使用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 regex的多个位置和良好的引用

    new RegExp("^.{0}[1-7]").test("6-4,4-4,6-4")
    
    2 回复  |  直到 5 年前
        1
  •  1
  •   Code Maniac    5 年前

    源可以是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))
    })
        2
  •  2
  •   bobble bubble    5 年前

    假设你不想放过 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 .