Home > Software engineering >  JS Regex - Match until the end of line OR a character
JS Regex - Match until the end of line OR a character

Time:10-04

Here is an example of what I'm trying to match:

Match everything after this:::
one
two
three
Match this also:::
one
two
three
___
but not this

My code:

const thing = /[^:]:::\n([\s\S]*)(_{3}|$)/gm

I want it to match everything AFTER ':::', but end either when it sees ___, or if that is not there, then the end of the text input, $.

It works for the FIRST example, but it continues to match the text after the ___ in the second example.

Any ideas how to make this right?

I'm only interested in the results in the first grouping. I had to group the (_{3}|$) otherwise it creates an infinite loop.

CodePudding user response:

The pattern [^:]:::\n([\s\S]*)(_{3}|$) that you tried matches too much because [\s\S]* will match all the way to the end. Then when at the end of string, there is an alternation (_{3}|$) matches either 3 times an underscore or the end of the string.

Then pattern can settle matching the end of the string.


You could use a capture group, and match all following lines that do not start with ___

[^:](:::(?:\n(?!___).*)*)
  • [^:] Match any char except :
  • ( Capture group 1
    • ::: Match literally
    • (?:\n(?!___).*)* Match all consecutive lines that does not start with ___
  • ) Close group 1

Regex demo

Or with a negative lookbehind if supported to get a match only, asserting not : to the left

(?<!:):::(?:\n(?!___).*)*

Regex demo

  • Related