我正在寻找一种方法,让正则表达式仅在单词未被 {c} text {/c} block 包围时匹配,并找到了一种方法
/(?![^{]*.*})(.+?)(?![^{]*.*})/g
但它会忽略由两个 {} 包围的任何内容(忽略 {} text{}),这不是我想要的。 正则表达式适用于我的聊天应用程序,它是用 Node js 编写的。 关键是我希望其他正则表达式不解析侧 {c} {/c} block 中的任何内容,甚至是其他 {c} {/c} block ,例如
{c} {c} text {/c} this is how you show codes {/c}
变成了
<pre> {c} text {/c} this is how you show codes </pre>
编辑:这就是我现在正在使用的。
var from = [
/(?![^{]*.*})`(.+?)`(?![^{]*.*})/g, /*bold `text`*/
/(?![^{]*.*})''(.+?)''(?![^{]*.*})/g, /*italics ''text''*/
/(?![^{]*.*})~~(.+?)~~(?![^{]*.*})/g, /*strikethrough ~text~*/
/(?![^{]*.*})@@(.+?)@@(?![^{]*.*})/g, /*code @@text@@*/
/{q}\s*(.+?)\s*{\/q}/g, /*quote {q}text{/q}*/
/{c}\s*(.+?)\s*{\/c}/g, /*preview {c}text{/c}*/
];
var to = [
"<strong>$1</strong>",
"<em>$1</em>",
"<span style='text-decoration:line-through'>$1</span>",
"<code>$1</code>",
"<blockquote>$1</blockquote><br />",
"<pre class=\"code\">$1</pre><br />",
];
最佳答案
下面的正则表达式将完成相同的工作。它将对包含在 {c}
和 {/c}
之间的整个字符串进行数学计算。
/{c}(.*){\/c}/g
使用纯Javascript:
var str = "{c} {c} text {/c} this codes {/c}";
var word1 = "{c}", word2 = "{/c}"; // words to be removed
var newWord1 = "<PRE>", newWord2 = "</PRE>"; // words need to be replaced
var fIndex = str.indexOf(word1); // getting first occurance of word1
str = str.replace(str.substring(0, word1.length), newWord1); // replacing it with newWord1
var lIndex = str.lastIndexOf(word2); // getting index of last occurance of word2
str = str.substring(0, lIndex) + newWord2 + str.substring(lIndex+word2.length, str.length); // and replacing it with newWord2
console.log(str);
关于javascript - 忽略 block 内单词的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40778232/