gpt4 book ai didi

javascript - 将多次出现的 && 替换为 ,将 %% 替换为 标记

转载 作者:行者123 更新时间:2023-12-01 01:30:48 25 4
gpt4 key购买 nike

我正在开发一个自定义解析函数,我需要用它来解析字符串&& 与 <b> 多次重复出现和 %% 与 <i>标签。

我尝试了这个正则表达式。

html = html.replace(/[&][&](.+?)[&][&]/g, '<b>$1</b>');
html = html.replace(/[%][%](.+?)[%][%]/g, '<i>$1</i>');

上面的替换对于我的意思是单个组来说效果很好

“&&This&& is a &&bold string&&”到“this is a bold string

这给出了奇怪的结果,我有重复的字符串

&&&&This&&&& is a &&bold string&& 

<b>&&This</b>&& is a <b>bold String</b>

需要帮助解析结束组和开始组,以将其替换为正确的 html 标签,例如

<b><b>This</b></b> is a <b>bold String</b>

如果可能的话,仅用一个 <b> 替换它标签

<b>This</b> is a <b>bold String</b>

最佳答案

一种选择是匹配尽可能多的 &尽可能连续,至少需要两个:

console.log(
'&&&&This&&&& is a &&bold string&&'
.replace(/&{2,}(.*?)&{2,}/g, '<b>$1</b>')
);

请注意,如果您想同时替换 &<b>标签和 %<i>标签,您可以使用单个正则表达式和访问对象的替换函数:

const obj = {
'&': 'b',
'%': 'i'
};
console.log(
'&&&&This&&&& is a &&bold string&& and there are italics %%here%%%'
.replace(
/([%&])\1+(.*?)\1{2,}/g,
(_, char, text) => `<${obj[char]}>${text}</${obj[char]}>`
)
);

如果您希望要求两端的组平衡,那么不仅要捕获组中的一个字符,还要捕获 & 的整个子字符串。或% s,这样您就可以稍后反向引用整个子字符串:

const obj = {
'&': 'b',
'%': 'i'
};
console.log(
'&&&&This&& is a &&bold string&& and there are italics %%here%%%'
.replace(
/(([%&])\2+)(.+?)\1/g,
(_, _2, char, text) => `<${obj[char]}>${text}</${obj[char]}>`
)
);

如果部分没有整齐地嵌套在其他部分中(例如 <b>foo<i>bar</b>baz</i> ),那么您必须使用原始方法来替换 && s,然后再次遍历字符串并替换 %% s:

console.log(
'&&&&This&& is a &&bold string&& and there are italics %%here%%%'
.replace(/(&{2,})(.+?)\1/g, '<b>$2</b>')
.replace(/(%{2,})(.+?)\1/g, '<i>$2</i>')
);

关于javascript - 将多次出现的 && 替换为 <b>,将 %% 替换为 <i> 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53293072/

25 4 0