简体   繁体   English

正则表达式匹配的OrgMode标签

[英]Regex matching OrgMode tags

I want to write an regex in JavaScript to match the tags in OrgMode format 我想用JavaScript编写正则表达式以匹配OrgMode格式的标签

Example: 例:

  • Sample title :tag1:tag2:tag3: 样本标题:tag1:tag2:tag3:

I have tested the following regex but it only matches the first and the last tags (tag1,tag3): 我已经测试了以下正则表达式,但它仅匹配第一个和最后一个标签(tag1,tag3):

\:\w+\:

Thanks 谢谢

My guess is that here an expression with start and end anchors might be desired, if we'd be validating: 我的猜测是,如果我们要验证的话,这里可能需要带有开始和结束锚点的表达式:

^((?=:\w+)(:\w+)+):$

Demo 1 演示1

 const regex = /^((?=:\\w+)(:\\w+)+):$/gm; const str = `:tag1:tag2:tag3: :tag1:tag2:tag3:tag4: :tag1:tag2:tag3:tag4:tage5: :tag1:tag2:tag3:tag4:tage5`; let m; while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } // The result can be accessed through the `m`-variable. m.forEach((match, groupIndex) => { console.log(`Found match, group ${groupIndex}: ${match}`); }); } 

Use 采用

/:(\w+)(?=:)/g

The value you need is inside Group 1. See the regex demo online . 您需要的值在第1组内部。请参见regex在线演示

The main point is the (?=:) positive lookahead: it checks (and requires) but does not consume the : to the right of the \\w+ pattern. 要点是(?=:)正向查找:它检查(并要求),但不使用\\w+模式右边的:

See JS demo below: 请参见下面的JS演示:

 var s = "Sample title :tag1:tag2:tag3:"; var reg = /:(\\w+)(?=:)/g; var results = [], m; while(m = reg.exec(s)) { results.push(m[1]); } console.log(results); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM