Search code examples
node.jsregexnumbersreadlineregex-lookarounds

RegEx for extracting the last combination of numbers from a paragraph


RegEx for extracting the last combination of numbers from a paragraph

E.g.:

“My ID is 112243 and my phone number is 0987654321. Thanks you.”

So I want to extract the phone number here which is the last combo of digits.


Solution

  • You can use this regex,

    \d+(?=\D*$)
    

    Here, \d+ selects one or more number and this positive lookahead (?=\D*$) ensures that if at all anything is present further ahead before end of string then it is not a digit (by using \D* before $).

    Regex Demo

    JS Code demo,

    const s = 'My ID is 112243 and my phone number is 0987654321. Thanks you.'
    
    console.log(s.match(/\d+(?=\D*$)/))