bobbylej
bobbylej

Reputation: 40

Regex: How to match anything till specific string or end of text

I'm trying to create a regex that will match anything between a specific string (# in this case) or between this string and the end of the text.

Currently, I have something like that: /^\# ([\s\S]*)\# /gm and I'm testing it on such a sample text:

# Group 1
## Section 1.1

# Group 2
## Section 2.1

# Group 3
Test

It returns one match with such a group inside:

Group 1
## Section 1.1

# Group 2
## Section 2.1


and should return three matches with these groups:

Group 1
## Section 1.1

Group 2
## Section 2.1

Group 3
Test

Any idea how I can achieve that?

Upvotes: 0

Views: 299

Answers (1)

The fourth bird
The fourth bird

Reputation: 163362

If a positive lookahead is supported, tou could repeat matching all lines that do not start with #

^# (.*(?:\r?\n(?!# ).*)*)
  • ^ Start of string
  • # Match # and a space
  • ( Capture group 1
    • .* Match the rest of the line
    • (?:\r?\n(?!# ).*)* Match a newline and all lines that do not start with #
  • ) Close group 1

Regex demo

Getting the value from group 1 for example with JavaScript

const regex = /^# (.*(?:\r?\n(?!# ).*)*)/gm;
const str = `# Group 1
## Section 1.1

# Group 2
## Section 2.1

# Group 3
Test`;
console.log(Array.from(str.matchAll(regex), m => m[1]));

Upvotes: 1

Related Questions