簡體   English   中英

匹配字符串開頭的正則表達式應該是什么

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

我有一個類似的字符串,我只想匹配每個{{xxxx}}模式的第一個'{'

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

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

我嘗試使用/(\\s|^|.){/g但此模式匹配

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

有人能指導我正確的方向嗎

您需要使用/(^|[^{]){/g (將其匹配並捕獲到組1的字符串開頭或除{之外的任何其他字符,然后匹配{ )並檢查組1是否在每個匹配RegExp#exec迭代。 然后,如果第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