gpt4 book ai didi

JavaScript 正则表达式字符串匹配/替换

转载 作者:行者123 更新时间:2023-11-29 19:00:20 24 4
gpt4 key购买 nike

给定字符串; “{abc}Lorem ipsum{/abc} {a}dolor{/a}”

我希望能够找到大括号“标签”的出现,将标签和索引存储在找到它的位置并将其从原始字符串中删除。我想为每次出现重复这个过程,但是因为每次索引必须正确时我都会删除部分字符串......我找不到所有索引然后在最后删除它们。对于上面的例子,应该发生的是;

  • 搜索字符串...
  • 在索引 0 处找到“{abc}”
  • 将{ tag: "{abc}", index: 0 } 压入数组
  • 从字符串中删除“{abc}”
  • 重复第一步,直到找不到更多的匹配项

鉴于此逻辑,“{/abc}”应该在索引 11 处找到 - 因为“{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 值中减去匹配长度,否则下一次迭代开始比预期更远(因为输入变短,而 lastIndex 不会在您调用 replace 删除 {...} 子字符串后得到更改):

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引用要牢记:

If your regular expression uses the "g" flag, you can use the exec() method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property (test() will also advance the lastIndex property).

关于JavaScript 正则表达式字符串匹配/替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47269607/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com