Search code examples
javascriptregexregex-lookaroundsend-of-line

Regex to create a group from an entire line, or just up to a given token


I'm using a JavaScript Regex Engine.

The regex ^(.*?)\s*(?=[*\[]).* will capture a group containing all the characters up to a [ or * character. It works well with these lines, matching the entire line and capturing the first section:

This should be captured up to here[ but no further]
This should be captured up to this asterisk* but not after it*

However, I would like to also capture an entire line if it contains neither of these characters:

This entire line should be captured.

This regex ^(.*?)\s*(?=[*\[]).*|^(.*)$ will match the entire line, but it will not capture anything in group \1.

Is it possible to modify the lookahead so that it will also find no more characters?


Solution

  • Just add an end of the line anchor inside the positive lookahead assertion.

    ^(.*?)\s*(?=[*\[]|$)
    

    DEMO