Lido Fernandez
Lido Fernandez

Reputation: 456

Regex for getting only the last N numbers in javascript

I've being trying to generate a regex for this string:

what I need is a way to get only the last 5 numbers from only 9 numbers

so far I did this:

 case.match(/\d{5}$/)

it works for the first 2 cases but not for the last one

Upvotes: 1

Views: 483

Answers (3)

jmcgriz
jmcgriz

Reputation: 3358

You can use a positive lookbehind (?<= ) to assert that your group of 5 digits is preceeded by a group of 4 digits without including them in the result.

/(?<=\d{4})\d{5}$/

var inputs = [
"test-123456789", // 56789
"test-1234-123456789", // 56789
"test-12345", //fail or not giving anything
]

var rgx = /(?<=\d{4})\d{5}$/

inputs.forEach(str => {
  console.log(rgx.exec(str))
})

Upvotes: 1

Hassan Sadeghi
Hassan Sadeghi

Reputation: 1326

You can try this:

var test="test-123456789";
console.log((test.match(/[^\d]\d{4}(\d{5})$/)||{1: null/*default value if not found*/})[1]);

This way supports default value for when not found any matching (look at inserted comment inline above code.).

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You may use

/\b\d{4}(\d{5})$/

See the regex demo. Get Group 1 value.

Details

  • \b - word boundary (to make sure the digit chunks are 9 digit long) - if your digit chunks at the end of the string can contain more, remove \b
  • \d{4} - four digits
  • (\d{5}) - Group 1: five digits
  • $ - end of string.

JS demo:

var strs = ['test-123456789','test-1234-123456789','test-12345'];
var rx = /\b\d{4}(\d{5})$/;
for (var s of strs) { 
  var m = s.match(rx);
  if (m) { 
     console.log(s, "=>", m[1]);
   } else {
     console.log("Fail for ", s);
   }
}

Upvotes: 7

Related Questions