我使用Regex提取格式为[a-zA-z] [0-9] {8}的格式,例如:K12345678我需要从字符串中提取此格式,并且此格式应正确匹配。但是如果这种情况下我的测试用例失败
这是我的Regex / [a-zA-Z] [0-9] {8} / g phonone号:9978434276 K12345678:我的模式
对于这种情况,它失败了。
我的样本代码
const expression = /[a-zA-Z][0-9]{8}/;
const content = "phone number:9978434276K12345678:My pattern"
let patternMatch = content.match(expression);
预期的输出是K12345678。我编写的Regex无法处理此问题。
您可以使用String.match(Regex)
"9978434276K12345678".match(/[a-zA-Z][0-9]{8}/)
它返回4个元素的数组:[ String coincidence
,index
:数字,input
:字符串,groups
:未定义]
只需保留元素0:coincidence
和1:即可index of the match
。
并使用它只是检查字符串是否至少匹配一个
/Regex/.test(String)
/[a-zA-Z][0-9]{8}/.test("9978434276K12345678")
它将返回true或false
USE表达式不带引号
const expression = /[a-zA-Z][0-9]{8}/;
const content = "phone number:9978434276K12345678:My pattern"
let patternMatch = content.match(expression);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句