Home > Mobile >  Find set of numbers after string without using lookbehind
Find set of numbers after string without using lookbehind

Time:03-02

I've been scratching my head for quite a while now. I am trying to get the set of numbers after certain string using Regex. I am using positive lookbehind but it is not supported in many browsers. So is there a way to build a pattern for this without using lookbehind?

From the below examples I only want to get the numbers after the string Test so it should only be 12345 and 67891. This is multiline.

String 1:

Test 12345

String 2:

Test 12345, 67891
Sample 0101, 0202

This is the pattern I used for both examples with lookbehind:

/(?<=Test )\d |(?<=, )\d /gm

CodePudding user response:

If I understand correctly, you want to match only the numbers on the line that starts with "Test", and not on any other lines. And it may have one or two numbers separated by commas. If you want to match the numbers and use them for something, use for example:

str.match(/Test (\d )(?:, (\d ))?/m);

It matches the string "Test " followed by a capturing group of digits, optionally followed by a non-following group consisting of a comma, a space, and another capturing group of digits.

This yields:

const str1 = "Test 12345";
const str2 = "Test 12345, 67891\nSample 0101, 0202";

str1.match(/Test (\d )(?:, (\d ))?/m);
// -> ['Test 12345', '12345', undefined, index: 0, input: 'Test 12345', groups: undefined]

This is an array of 3 elements: the first element is the complete match, which you don't need in this case. The rest of the elements are one or two matching groups of digits. This means you can get your answer using:

str1.match(/Test (\d )(?:, (\d ))?/m).slice(1).filter(Boolean);
// -> ['12345']

Similarly, for the multiline string:

str2.match(/Test (\d )(?:, (\d ))?/m).slice(1).filter(Boolean);
// -> ['12345', '67891']

You could also first capture the lines you want and then get the numbers out, and you could even have more matching lines and numbers per line:

"Test 12345, 234, 23, 45\nSample 2, 5, 4\nTest 12"
  .match(/^Test . $/mg)
  .map(line => line.match(/\d /g))
  .flat();
// -> ['12345', '234', '23', '45', '12']
  • Related