JavaScript RegExp:匹配指定分隔符前的所有符合格式条目
*** DIVIDER Let's start by figuring out why your initial regex didn't work, then fix it up properly.
Why Your First Attempt Failed
Your regex ^[\S]*:.*(?=[\S]*\sDIVIDER) uses a positive lookahead that expects the matched line to be immediately followed by non-whitespace characters, a space, and "DIVIDER". But in your input, the *** DIVIDER sits on its own separate line after the valid actions. The lookahead can't "see" across the newline in this context, so it never triggers a match—hence why it didn't work.
Working Regex Options
Option 1: Directly Match Pre-Divider Lines (PCRE Compatible)
If you're using a regex engine that supports multi-line lookaheads (like PCRE), this regex will directly target only the action lines before the divider:
^[\S]+:.*$(?=(?:\n(?!\*\*\* DIVIDER).)*\n\*\*\* DIVIDER)
How it works:
^[\S]+:.*$: Stays true to your original pattern, matching lines that start with non-whitespace characters, followed by a colon and any content to the end of the line.(?=(?:\n(?!\*\*\* DIVIDER).)*\n\*\*\* DIVIDER): The positive lookahead checks that after the current line, there are zero or more lines that don't start with*** DIVIDER, followed by the actual divider line itself. This ensures we only match lines that live before the divider.
Option 2: Capture the Pre-Divider Block First (Easier to Maintain)
If you want something more straightforward, first capture all content before the divider, then apply your original regex to that block. Use this regex to grab the pre-divider content:
\A(.*?)(?=\n\*\*\* DIVIDER)
Then run your original ^[\S]*:.*/gm regex on the captured group to pull out the action lines. This approach is often simpler to read and tweak later.
Option 3: Negative Lookbehind (For Modern Engines)
If your regex engine supports variable-length lookbehinds (like JavaScript ES2018+ or PCRE), this regex will exclude any lines that come after the divider:
^[\S]+:.*$(?<!\*\*\* DIVIDER\n.*)
It works by checking that the current line isn't preceded by the divider line and any content that comes after it.
Testing with Your Input
For your sample input:
john: buys beer
sam: eats bananas
*** DIVIDER
irrelevant actions
luis: walking
All valid options will only match these two lines:
john: buys beersam: eats bananas
内容的提问来源于stack exchange,提问作者knitevision

