how to extract the fifth digit in a pool of digits through regex in javascript

Viewed 64

I am trying to extract the fifth and sixth value present in the stream through regex. The stream is 55600000556000. These are separate values 556000 0 0 556000. I need the zeros that are present in between this value.

I tried [0-9]{1,10}$ but its selecting the string from end. https://regex101.com/r/rVRShm/1

Can anybody help me please in getting the zeros that are present in the middle!!!

3 Answers

Try this:

const regex = /[0-9]{6}([0-9]{1})([0-9]{1})[0-9]{6}/;

const str = '55600000556000';

const [ wholeStr, firstMatch, secondMatch ] = regex.exec(str);

console.log(firstMatch, secondMatch);

One approach would be to use string match with the following regex pattern:

\b556000(\d+?)556000\b

var input = "55600000556000";
var matches = input.match(/\b556000(\d+?)556000\b/);
console.log(matches[1]);

You could also test if the string consists of only and 14 digits using ^\d{14}$ and then get the fifth and sixth character.

const s = "55600000556000";
if (/^\d{14}$/.test(s)) {
  console.log(s.charAt(4) + s.charAt(5));
}

Related