我正在寻找regexp的方法,只有在{c} text {/ c}块没有包围该单词时才匹配,并且找到了一种方法
/(?![^{]*.*})(.+?)(?![^{]*.*})/g
但它忽略了两个{}({} text {}被忽略的任何环绕声,这不是我想要的。 正则表达式是我的聊天应用程序,它是用节点js编写的。 关键是我希望其他正则表达式不解析{c} {/ c}块中的任何内容,甚至是其他{c} {/ c}块,例如
{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 />",
];
答案 0 :(得分:1)
以下正则表达式将执行相同的工作。它会覆盖{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);
&#13;