1

I want to match string between two string with Regex including newlines.

For example, I have the next string:

{count, plural,
  one {apple}
  other {apples}
} 

I need to get string between plural, and one. It will be \n*space**space*. I tried this Regex:

/(?:plural,)(.*?)(?:one)/gs

It works, but not in JS. How to do that with JavaScript?

Meadow Lizard
  • 330
  • 2
  • 7
  • 19

2 Answers2

5

To match the everything including newline character, you can use [\s\S] or [^]

var str = `{count, plural,
  one {apple}
  other {apples}
} `;
console.log(str.match(/(?:plural,)([\s\S]*?)(?:one)/g));
console.log(str.match(/(?:plural,)([^]*?)(?:one)/g));
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
  • `m` here is redundant. – revo Dec 10 '17 at 15:12
  • Yes, `m` is redundant Thanks for pointing out. Do you know the reason? – Hassan Imam Dec 10 '17 at 15:23
  • 2
    Simply because `m` affects mean of `^` / `$` anchors to be start / end of subject string (default behavior) or start / end of line. I think what you are referring to as multi-line is dotall `s` flag which enables `.` to accept newline characters as well. Being not supported, `s` will be shipped with ES2018, hopefully. – revo Dec 10 '17 at 15:30
  • Thanks @revo for the explanation. :) – Hassan Imam Dec 10 '17 at 15:33
1

It doesn´t work because your testing with the wrong regex engine.

 `/s` does not exist in the JS regex engine, only in pcre

It must be something like:

/(?:plural,)((.|\n)*?)(?:one)/g

Hope it helps.

Alex
  • 320
  • 4
  • 9