gpt4 book ai didi

javascript - 如何在文本中获取自定义标签,并放入另一个文本?

转载 作者:行者123 更新时间:2023-12-04 12:17:51 27 4
gpt4 key购买 nike

标题问题可能不容易理解。希望您能在下面了解我的详细信息。
我在下面有句子数据,有一些标签,用 [tn]tag[/tn] 表示:

const sentence = `[t1]Sometimes[/t1] that's [t2]just the way[/t2] it has to be. Sure, there
were [t3]probably[/t3] other options, but he didn't let them [t4]enter his mind[/t4]. It
was done and that was that. It was just the way [t5]it[/t5] had to be.`
我有句子的一部分。
const parts = [
"Sometimes that's just the way",
"it has to be",
"Sure,",
"there were probably other options,",
"but he didn't let them enter his mind.",
"It was done and that was that.",
"It was just the way it had to be."
];

目标是使用上面的句子在每个部分上添加标签。
const expectedOutput = [
"[t1]Sometimes[/t1] that's [t2]just the way[/t2]",
"it has to be",
"Sure,",
"there were [t3]probably[/t3] other options,",
"but he didn't let them [t4]enter his mind[/t4].",
"It was done and that was that.",
"It was just the way [t5]it[/t5] had to be."
];
到目前为止,我尝试过的内容如下,但似乎没有意义,而且我什么也没做。
  • 做一个克隆句子,并删除所有标签。 (代码如下)
  • 找出句子中的所有部分。
  • [问题是我不知道如何重新放置标签]

  • 我想问有没有机会实现它?如何。谢谢
    export const removeTags = (content) => {
    content = content.replace(/([t]|[\/t])/g, '');
    return content.replace(/([t\d+]|[\/t\d+])/g, '');
    };

    最佳答案

    对于正则表达式的答案:/\[t\d+\]([^[]*)\[\/t\d+\]/g将匹配包括标签在内的所有单词,然后对这些标签中的所有单词进行分组。

    let regex = /\[t\d+\]([^[]*)\[\/t\d+\]/g;
    let matches = [], tags = [];
    var match = regex.exec(sentence);
    while (match != null) {
    tags.push(match[0]);
    matches.push(match[1]);
    match = regex.exec(sentence);
    }
    现在我们只需要替换所有 matchestags parts 内部
    let lastSeen = 0;
    for (let i = 0; i < parts.length; i++) {
    for (let j = lastSeen; j < matches.length; j++) {
    if (parts[i].includes(matches[j])) {
    lastSeen++;
    parts[i] = parts[i].replaceAll(matches[j], tags[j])
    } else if (j > lastSeen) {
    break;
    }
    }
    }
    这是查看正则表达式的链接: regex101
    这里有一个 JSFiddle 可以查看全部内容 JSFiddle

    关于javascript - 如何在文本中获取自定义标签,并放入另一个文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69432894/

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