![](/img/trans.png)
[英]Replace part of string with variable with Regex(Regular expression) condition match javascript
[英]JavaScript Regular Expression String Match/Replace
給定字符串; “ {abc} Lorem ipsum {/ abc} {a}美元{/ a}”
我希望能夠找到大括號“標簽”的出現,將標簽和索引存儲在找到的位置,並將其從原始字符串中刪除。 我想為每次出現重復此過程,但是因為每次索引必須正確時我都會刪除部分字符串...我找不到所有索引,然后在末尾將其刪除。 對於上面的示例,應該發生的事情是:
在這種邏輯下,應該在索引11處找到“ {/ abc}”,因為“ {abc}”已被刪除。
我基本上需要知道這些“標簽”在哪里開始和結束,而實際上並沒有將它們作為字符串的一部分。
我幾乎在使用正則表達式,但有時會跳過出現的情況。
let BETWEEN_CURLYS = /{.*?}/g; let text = '{abc}Lorem ipsum{/abc} {a}dolor{/a}'; let match = BETWEEN_CURLYS.exec(text); let tags = []; while (match !== null) { tags.push(match); text = text.replace(match[0], ''); match = BETWEEN_CURLYS.exec(text); } console.log(text); // should be; Lorem ipsum dolor console.log(tags); /** * almost there...but misses '{a}' * [ '{abc}', index: 0, input: '{abc}Lorem ipsum{/abc} {a}dolor{/a}' ] * [ '{/abc}', index: 11, input: 'Lorem ipsum{/abc} {a}dolor{/a}' ] * [ '{/a}', index: 20, input: 'Lorem ipsum {a}dolor{/a}' ] */
您需要從正則表達式lastIndex
值中減去匹配長度,否則下一次迭代的啟動將比預期的要長(因為輸入變得更短,並且在調用replace
刪除{...}
子字符串后, lastIndex
不會更改):
let BETWEEN_CURLYS = /{.*?}/g; let text = '{abc}Lorem ipsum{/abc} {a}dolor{/a}'; let match = BETWEEN_CURLYS.exec(text); let tags = []; while (match !== null) { tags.push(match); text = text.replace(match[0], ''); BETWEEN_CURLYS.lastIndex = BETWEEN_CURLYS.lastIndex - match[0].length; // HERE match = BETWEEN_CURLYS.exec(text); } console.log(text); // should be; Lorem ipsum dolor console.log(tags);
請記住更多RegExp#exec
參考:
如果您的正則表達式使用“
g
”標志,則可以多次使用exec()
方法在同一字符串中查找連續的匹配項。 這樣做時,搜索將從正則表達式的lastIndex
屬性指定的str
的子字符串開始(test()
還將使lastIndex
屬性前進)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.