字符串之间的正则表达式匹配

时间:2021-02-16 04:01:27

标签: regex regex-group

我使用正则表达式提取了一个格式为 [a-zA-z][0-9]{8} 的模式,例如:K12345678 我需要从字符串中提取这个模式,这个模式应该正确匹配 我尝试了以下但我的测试用例如果在这种情况下失败

这是我的正则表达式 /[a-zA-Z][0-9]{8}/g 电话号码:9978434276K12345678:我的模式

对于这种情况,它失败了。

我的示例代码

const expression = /[a-zA-Z][0-9]{8}/;
const content = "phone number:9978434276K12345678:My pattern"
let patternMatch = content.match(expression);

预期的输出是 K12345678。我写的正则表达式没有处理这个。

1 个答案:

答案 0 :(得分:2)

你可以使用 String.match(Regex)

"9978434276K12345678".match(/[a-zA-Z][0-9]{8}/)

它返回一个包含 4 个元素的数组:[String coincidence, index: Number, input: String, groups: undefined]

只保留元素 0:coincidence 和 1:index of the match

并使用它来检查字符串是否至少匹配一个

/Regex/.test(String)
/[a-zA-Z][0-9]{8}/.test("9978434276K12345678")

它会返回真或假

USE 不带引号的表达式

const expression = /[a-zA-Z][0-9]{8}/;
const content = "phone number:9978434276K12345678:My pattern"
let patternMatch = content.match(expression);