1

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.

Dalorzo
  • 19,834
  • 7
  • 55
  • 102
Veronica
  • 181
  • 1
  • 11

3 Answers3

3

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*$)/))
Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36
1

var string = "My ID is 112243 and my phone number is 0987654321. Thanks you";
var numbers = string.match(/\d+/g).map(Number);
console.log(numbers);

It will give you all combo of numbers in an array. You can choose which one you want.

Kirsten Phukon
  • 314
  • 3
  • 17
1

You can also use a simple regex like ^.*\b(\d+)

var str = 'My ID is 112243 and my phone number is 0987654321. Thanks you';
var num = str.match(/^.*\b(\d+)/)[1];
console.log(num);
  • Greedy .* will consume anything before the last \b word boundary followed by \d+ digits.
  • The parenthesis around \d+ will capture the stuff inside to [1]
  • If input is a multiline string, use such as [\s\S]* instead of .* to skip over newlines.
bobble bubble
  • 16,888
  • 3
  • 27
  • 46