gpt4 book ai didi

javascript - javascript中的 token 替换

转载 作者:行者123 更新时间:2023-11-30 18:53:56 27 4
gpt4 key购买 nike

我需要实现的是

在字符串中查找模式,存储匹配项将匹配项替换为唯一标记,以便稍后可以将标记替换为之前找到的匹配项。

解释

例如我有一组模式

paterns = [/Mr\.\s/,/Mrs\.\s/];


stringSubject = "Mr. john is an expert. mrs. john is no less. mr. watson know this very well";

提取匹配后它可能看起来像(不区分大小写的匹配)

stringSubject = "{1} john is an expert. {2} john is no less. {3} watson know this very well";

token 数组可能看起来像

tokens = ["Mr.","mr.","mrs."]

stringSubject = "{1} john is an expert. {3} john is no less. {2} watson know this very well";

//处理stringSubject之后

token 被替换为

stringSubject = "Mr. john is an expert. mrs. john is no less. mr. watson know this very well";

这样即使在对匹配模式执行不区分大小写的操作后,也能按原样检索原始字符串。

如何使用正则表达式完成此操作?

最佳答案

这个怎么样?

var stringSubject = "Mr. john is...",
patterns = [/Mr\.\s/, /Mrs\.\s/],
currentTokenIndex = 0,
tokens = [/* this is where the matches will be stored */];

for (var i = -1, l = patterns.length; ++i < l;) {
stringSubject = stringSubject.replace(patterns[i], function(match){
tokens[currentTokenIndex] = match;
return '{' + currentTokenIndex++ + '}';
});
}

stringSubject; // <= "{0}john is..."

// Later:
stringSubject = stringSubject.replace(/\{(\d+?)\}/g, function(match, index){
return tokens[index];
});

stringSubject; // <= "Mr. john is..."

关于javascript - javascript中的 token 替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2850948/

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