求助:编写JavaScript正则匹配OrgMode标签的问题
Ah, I see the issue here—your original regex \:\w+\: is missing the middle tags because of how regex matching works by default. Let me break this down and fix it for you.
When you use \:\w+\: with global matching, it finds :tag1: first. Regex matches are non-overlapping, so after matching that, the engine skips all the characters it already processed (including the closing : of tag1). Next, it looks for another :\w+: starting from the t in tag2—which doesn’t start with a :, so it keeps scanning until it finds :tag3:. That’s why tag2 gets left out.
The Fix: Zero-Width Lookaround Assertions
The solution is to use lookaround assertions, which let you check for the surrounding : without actually consuming them. This way, the engine can reuse the same : to match the next tag.
Here’s the regex you need:
/(?<=:)\w+(?=:)/g
Let’s break down each part:
(?<=:): Positive lookbehind assertion—checks that the current position is immediately preceded by a:, but doesn’t include the:in the match result.\w+: Matches one or more word characters (letters, numbers, underscores)—this is your actual tag content.(?=:): Positive lookahead assertion—checks that the current position is immediately followed by a:, without including it in the match.
JavaScript Usage Example
const orgText = "Sample title :tag1:tag2:tag3:"; const tagRegex = /(?<=:)\w+(?=:)/g; const tags = orgText.match(tagRegex); console.log(tags); // Output: ["tag1", "tag2", "tag3"]
Fallback for Older Environments
If you need to support older JavaScript versions that don’t support lookbehind assertions (pre-ES2018), use a two-step approach:
const orgText = "Sample title :tag1:tag2:tag3:"; // First extract the full tag block const tagBlockMatch = orgText.match(/:\w+(?::\w+)*:/); if (tagBlockMatch) { const tagBlock = tagBlockMatch[0]; // Remove leading/trailing colons and split into tags const tags = tagBlock.slice(1, -1).split(':'); console.log(tags); // Output: ["tag1", "tag2", "tag3"] }
That should capture all your OrgMode tags perfectly!
内容的提问来源于stack exchange,提问作者ashraf

