-2

I'm trying to get the number from string between '_text' word and '_' char. I tried my regex on regex101 page and there it's working but in my code I didn't get anything.

const s = 'line0_text4_89yf9sd9afg977f8gds9g9fdg'
const regexToGetNumber = '/_text(.*?)_/gm';
const result = s.match(regexToGetNumber);  // and it's null

In that case I expect the 4.

Monkey D. Teach
  • 137
  • 2
  • 8
  • 2
    TLDR: Remove single quotes and the `gm` flags, use `const regexToGetNumber = /_text(.*?)_/;`. Since the result is in Group 1, access it: `s.match(regexToGetNumber)?.[1]` – Wiktor Stribiżew Jul 12 '23 at 13:20

1 Answers1

1

Your main issue is that you quoted the expression. The String prototype does not have a match method. It needs to be a regex literal or RegExp object.

You can use a positive look-behind (?<=_text) and a positive look-ahead (?=_) and wrap the expression [^_]* (zero or more non-underscores).

You can extract the first match with destructuring the result array.

const str = 'line0_text4_89yf9sd9afg977f8gds9g9fdg';
const regexToGetNumber = /(?<=_text)[^_]*(?=_)/gm;
const [value] = str.match(regexToGetNumber) ?? [];

console.log(value); // '4'

If you have a regex string, you need to call the RegExp constructor:

const str = 'line0_text4_89yf9sd9afg977f8gds9g9fdg';
const regexToGetNumber = new RegExp('(?<=_text)[^_]*(?=_)', 'gm');
const [value] = str.match(regexToGetNumber) ?? [];

console.log(value); // '4'
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132