包含不同字母的正则表达式问题
Regular Expression question that include different letters
我正在尝试找出只接受以下字符串的正则表达式。
7 和 8 个数字:“1234567”和“12345678”
7和8个以T开头的数字:'T234567'和'T2345678'
7和8个D开头的数字:'D234567'和'D2345678'
7和8个TD开头的号码:'TD34567'和'TD345678'
我的正则表达式是:
/^(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}
匹配 T
或 D
和 6-7 位数字
|
或
TD\d{5,6}
匹配TD
和5-6位数字
)
关闭非捕获组
$
字符串结束
我实际上是在发布了这个问题之后才弄明白的。只需在 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
经过大量测试。
我正在尝试找出只接受以下字符串的正则表达式。
7 和 8 个数字:“1234567”和“12345678”
7和8个以T开头的数字:'T234567'和'T2345678'
7和8个D开头的数字:'D234567'和'D2345678'
7和8个TD开头的号码:'TD34567'和'TD345678'
我的正则表达式是:
/^(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}
匹配T
或D
和 6-7 位数字|
或TD\d{5,6}
匹配TD
和5-6位数字
)
关闭非捕获组$
字符串结束
我实际上是在发布了这个问题之后才弄明白的。只需在 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
经过大量测试。