【问题标题】:How to match only specific characters in a given string with regex?如何使用正则表达式仅匹配给定字符串中的特定字符?
【发布时间】:2023-01-11 00:22:51
【问题描述】:

我想要一个特定的值,必须具有的值:

  • 长度应为 11。

  • 第一个数字应该是 0。

  • 第二个数字应该是 1。

  • 第三个数字应该是 0、1、2、5。

  • 然后匹配从第四位到末尾的任何数字。

  • 如果第三位是 1,那么最后两位(第 10、11)应该相同。

  • 如果第三位是2,那么第8、9位应该相同。

输入字符串和预期结果。

01012345678          -----> allowed.
0101234a5678         -----> not allowed., letter exists.
01112345688          -----> allowed, 10th, 11st are the same
01112345677          -----> allowed, 10th, 11st are the same
01112345666          -----> allowed, 10th, 11st are the same
01112345689          -----> not allowed..10th, 11st different
01112345-678         -----> not allowed..hyphen exists.
01298765532          -----> allowed..8th, 9th are the same.
01298765732          -----> not allowed, 8th, 9th different.
01298765mm432        -----> not allowed, more than 11 chars.
01500011122          -----> allowed..
020132156456136      -----> not allowed..more than 11 digit.
01530126453333       -----> not allowed..more than 11 digit.
00123456789          -----> not allowed.. second digit.

这是我对 regex101 的尝试,^01[0125][0-9]{8}$https://regex101.com/r/cIcD0R/1 但它忽略了特定情况,它也适用于特定情况。

【问题讨论】:

  • 我建议应该使用正则表达式来验证这一点,但是在一个正则表达式中执行所有操作将不可避免地导致非常脆弱(并且可能难以理解)的表达式;考虑为最终必须破译和更新相关代码的可怜人写作。

标签: javascript regex


【解决方案1】:

您可以使用带有 2 个捕获组和反向引用的交替:

^01(?:[05]d{8}|1d{6}(d)|2d{4}(d)dd)$

解释

  • ^ 字符串开始
  • 01字面匹配
  • (?: 替代方案的非捕获组
    • [05]d{8} 匹配 05 和 8 位数字
    • | 或者
    • 1d{6}(d) 匹配1,然后是 6 位数字,捕获第 1 组中的单个数字,后跟反向引用以匹配相同的数字
    • | 或者
    • 2d{4}(d)dd 匹配2,然后是 4 位数字,捕获第 2 组中的单个数字,然后是反向引用以匹配相同的数字并匹配最后 2 位数字
  • )关闭非捕获组
  • $字符串结尾

看到一个regex101 demo

【讨论】:

  • 这并不是要批评你的回答,但为了回应这个问题,我会参考我之前的评论——对这个问题——”[这导致]一个非常脆弱(并且可能难以理解)的表达;“你认为你可以解释这是如何工作的(在答案空间),为了我的利益以及帮助 OP 和未来的访客?
  • @DavidThomas 我目前正在写它:-)
  • 你及时找到了我,好的正则表达式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-08
相关资源
最近更新 更多