简体   繁体   中英

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

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

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

I tried with /(\\s|^|.){/g but this pattern matches

{ {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. Then, if Group 1 matched, increment the match index:

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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