【问题标题】:Regex search two different strings and replace with different values正则表达式搜索两个不同的字符串并替换为不同的值
【发布时间】:2026-01-28 23:10:01
【问题描述】:

所以我需要以这种形式处理一个字符串:

<Text to be highlighted> word word word word <text again> something ...

所以目标是用&lt;b&gt;替换所有开头的,用&lt;/b&gt;替换结束的>。但是我不能使用两个不同的正则表达式一个来查找 另一个来查找 > 因为当我运行第二个时,关闭 >最近创建的 b 标签也将被替换。

我完全清楚 javascript 和字符串管理有很多解决方法,但是我想为此使用正则表达式。

这是我到目前为止所做的,但我之前说过的问题。

const expOpening = new RegExp(/</gm);
const expClosing = new RegExp(/>/gm);

input.replace(expOpening, '<b>');
input.replace(expClosing, '</b>');

【问题讨论】:

    标签: javascript regex replace text-formatting


    【解决方案1】:

    全局正则表达式替换应该在这里工作:

    var input = "<Text to be highlighted> word word word word <text again> something ...";
    var output = input.replace(/<(.*?)>/g, "<b>$1</b>");
    console.log(input + "\n" + output);

    【讨论】:

    • 非常感谢,羡慕你们这些精通正则表达式的人!
    • @CésarCastroAroche 查看Wiktor's profile,他是本网站上最优秀的正则表达式人员之一:-)
    最近更新 更多