3

I have some text (which some of you will recognize as part of a fortune file)

A day for firm decisions!!!!!  Or is it?
%
A few hours grace before the madness begins again.
%
A gift of a flower will soon be made to you.
%
A long-forgotten loved one will appear soon.

Buy the negatives at any price.
%

As can be seen, this contains both single line text and block text (as seen in the last fortune).

I currently have a regex that will capture all single line fortunes, however, it does not capture the multiline fortune.

(?<=%\n)(.*?)(?=\n%)

I understand that there is a /m multiline option, however, I do not want the entire regex to be multiline enabled (I have not gotten it to work at all in that way).

So my question is: How can I select multiline text blocks between delimiters as a local capture group? It should be noted that I will be using this in JavaScript.

Tanishq dubey
  • 1,522
  • 7
  • 19
  • 42

2 Answers2

1

Try this,

str.split(/\n%\n/)

This splits the string by lines that contain % only.

akuhn
  • 27,477
  • 2
  • 76
  • 91
0

To match a newline, you can use [^] or [\s\S]. The dot does not match. This has nothing to do with the m flag, which has to do with whether anchors (^ and $) match at the beginning and ends of lines. Other regexp engines have syntax for making the dot match newlines, and one is being proposed for a future version of JS, but for the time being you'll have to use one of the approaches above.

[^] literally means "match any character which is not nothing", which, as it turns out, includes a newline; [\s\S] literally means "match any character which is either whitespace or not whitespace", which also includes a newline.

Assuming your regexp currently works except for this newline problem, use

(?<=%\n)([^]*?)(?=\n%)

See this SO question. There is some information on this in Eloquent JavaScript. The TC39 proposal (for a new s flag) is here.

Community
  • 1
  • 1