首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Javascript - regex用于验证特定位置的字符

Javascript - regex用于验证特定位置的字符
EN

Stack Overflow用户
提问于 2019-09-29 16:09:44
回答 2查看 703关注 0票数 2

我希望使用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]

如果以上匹配为false,则应返回true。

让我知道如何增强下面来验证多个位置和javascript regex的良好参考。

代码语言:javascript
运行
复制
new RegExp("^.{0}[1-7]").test("6-4,4-4,6-4")
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-09-29 16:24:15

源可以是7个字符,也可以是11个字符,并且在末尾没有。specified by op

您可以使用

代码语言:javascript
运行
复制
^(?:[1-7]-[1-7],){1,2}(?:[1-7]-[1-7])$

Regex demo

代码语言:javascript
运行
复制
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
EN

Stack Overflow用户

发布于 2019-09-29 16:20:27

假设你不想通过1-1,,1-1,我会尝试

代码语言:javascript
运行
复制
^(?:[1-7]-[1-7],?\b)+$

在Regex101上看到这个演示

  • 用于量化组的,? 可选逗号
  • \b匹配一个字界 (确保每个1-1之间都有一个逗号)

匹配一个或多个1-1。如果您想匹配2到3,最后

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58156976

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档