目前,我正在尝试在我的web应用程序中实现我自己对不和谐的感觉。我这样做的方法很简单,就是链接替换方法,每次检查并用适当的HTML标记替换语法(我做了清理,不用担心)。
let description = description.replace(/\`{3}([\S\s]*?)\`{3}/g, '<code>$1</code>')
.replace(/\`(.*)\`/g, '<code class="inline">$1</code>')
.replace(/~~([\S\s]*?)~~/g, '<s>$1</s>')我面临的问题是regex还匹配整个代码块内部和内联代码中。这种行为是不需要的。
**bold and
*italic and
__underline and
~~strikethrough~~__***
`~~Not strikethrough~~`
~~`Strikethrough`~~
Normal text而不是罢工
~~```
Strikethrough
```~~**大胆和
*斜体和
__underline和
strikethrough__***
~~Not strikethrough~~
Strikethrough
正常文本
我尝试过这样的方法:/(?<!`[\S\s])\*([\S\s]*?)\*(?!`)/g,但我无法让它像预期的那样工作。
我仍然在学习regex,并继续发现很难把我的头绕过去,所以任何和所有的帮助都是非常感谢的。
.2021年1月4日对不起,我之前没有澄清,但风格应该是“不稳定的”,或者换句话说,可以组合起来,例如***strong and italic***应该变成强的和斜体的。
我更新了输入文本(见上文),以便更好地封装所有可能的用例。
发布于 2021-01-03 20:44:38
您可以使用
let text = "**bold and \n*italic and \n__underline and \n~~strikethrough~~__***\n\n`~~Not strikethrough~~`\n~~`Strikethrough`~~\n\nNormal text\n\n```\n~~Not strikethrough~~\n```\n\n~~```\nStrikethrough\n```~~\n\n**bold and \n*italic and \n__underline and \n~~strikethrough~~__***\n\n`~~Not strikethrough~~`\n~~`Strikethrough`~~\n\nNormal text";
const re = /<code(?:\s[^>]*)?>[\s\S]*?<\/code>|`{3}([\S\s]*?)`{3}|`([^`]*)`|~~([\S\s]*?)~~|\*{2}([\s\S]*?)\*{2}(?!\*)|\*([^*]*)\*|__([\s\S]*?)__/g;
let tmp="";
do {
tmp = text;
text = text.replace(re, (match, a, b, c, d, e, f) => f ? `<u>${f}</u>` : e ? `<i>${e}</i>` : d ? `<b>${d}</b>` : c ? `<s>${c}</s>` : b ? `<code class="inline">${b}</code>` : a ? `<code>${a}</code>` : match);
}
while (text != tmp);
console.log(text);
见regex演示。
重点是为一次传递设计单个正则表达式,并将字符串部分捕获到单独的组中,以应用不同的替换逻辑。
有三种选择匹配
`{3}([\S\s]*?)`{3} -三重星号之间的任何子字符串将其捕获到第1组(x)`([^`]*)` -单个星号之间的任何子字符串将其捕获到第2组(y)~~([\S\s]*?)~~ - ~~将其捕获到第3组(z)之间的任何子字符串见regex演示。
https://stackoverflow.com/questions/65553307
复制相似问题