简体   繁体   English

匹配字符串开头的正则表达式应该是什么

[英]What should be the regex to match the start of a string

I have a string something like and I want to match just the first '{' of every {{xxxx}} pattern 我有一个类似的字符串,我只想匹配每个{{xxxx}}模式的第一个'{'

{ {abcd}} { {efg}} { {hij}} { {abcd}} { {efg}} { {hij}}

{ {abcd}} { {efg}} { {hij}} { { {abcd}} { {efg}} { {hij}} {

I tried with /(\\s|^|.){/g but this pattern matches 我尝试使用/(\\s|^|.){/g但此模式匹配

{ {abcd} }{ {efg} }{ {hij}} { {abcd} } { {efg} } { {hij}}

Can some one guide me in the right direction 有人能指导我正确的方向吗

You need to use /(^|[^{]){/g (that matches and captures into Group 1 start-of-string or any char other than { , and then matches a { ) and check if Group 1 matched at each RegExp#exec iteration. 您需要使用/(^|[^{]){/g (将其匹配并捕获到组1的字符串开头或除{之外的任何其他字符,然后匹配{ )并检查组1是否在每个匹配RegExp#exec迭代。 Then, if Group 1 matched, increment the match index: 然后,如果第1组匹配,则增加匹配索引:

 var re = /(^|[^{]){/g; var str = "{{abcd}}{{efg}}{{hij}}\\n{{abcd}}{{efg}}{{hij}}{"; // 0 8 15 23 31 38 45 var m, indices = []; while ((m = re.exec(str)) !== null) { indices.push(m.index + (m[1] ? 1 : 0)); } console.log(indices); 

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

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