包含不同字母的正则表达式问题

Regular Expression question that include different letters

我正在尝试找出只接受以下字符串的正则表达式。

我的正则表达式是:

/^(T|[0-9]){1}(D|[0-9]){1}([0-9]){5,6}$/

但它没有通过我对 'D234567' 和 'D2345678'

的单元测试

您可以将模式写为:

^(?:\d{7,8}|[TD]\d{6,7}|TD\d{5,6})$

说明

  • ^ 字符串开头
  • (?: 备选方案的非捕获组
    • \d{7,8}匹配7-8位数字
    • |
    • [TD]\d{6,7} 匹配 TD 和 6-7 位数字
    • |
    • TD\d{5,6}匹配TD和5-6位数字
  • )关闭非捕获组
  • $ 字符串结束

Regex demo.

我实际上是在发布了这个问题之后才弄明白的。只需在 T| 之后添加 |D像这样。

/^(T|D|[0-9]){1}(D|[0-9]){1}([0-9]){5,6}$/

const r = /^(?=.{7,8}$)T?D?\d+$/

是最简单的解决方案。以下是所发生情况的细目分类:

import {lookAhead, maybe, sequence, suffix} from "compose-regexp"

const r = sequence(
  // start anchor
  /^/,
  // are there exactly 7 or 8 characters before the end?
  lookAhead(suffix([7,8], /./), /$/),
  // optionally match a 'T'
  maybe('T'),
  // optionally match a 'D'
  maybe('D'),
  // match numbers until the end
  suffix('+', /\d/),
  /$/
)

你可以试试here

经过大量测试。