Search code examples
regexregex-group

Regex Match in between Strings


I using Regex to extract a pattern which is of the form [a-zA-z][0-9]{8} Ex:K12345678 I need to extract this pattern from a string and this pattern should be matched properly I tried the below but my testcase if failing for this scenario

This is my Regex /[a-zA-Z][0-9]{8}/g phonne number:9978434276K12345678:My pattern

For this scenario it is failing.

My Sample Code

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

The expected output is K12345678.The Regex which I wrote does not handle this.


Solution

  • You can use String.match(Regex)

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

    It returns an array of 4 elements: [String coincidence, index: Number, input: String, groups: undefined]

    just stay with the element 0: coincidence and 1: index of the match.

    and use this just to check that the string matches at least one

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

    It will return true or false

    USE expression without quotation marks

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