javascript - 忽略 block 内单词的正则表达式

标签 javascript

我正在寻找一种方法,让正则表达式仅在单词未被 {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/

相关文章:

javascript - 一个关于-1和i--的简单for循环问题

javascript - 新行之前的正则表达式检查字符不起作用

javascript - React Setstate 在 JSON 化后使我的状态项未定义

javascript:控制台日志使用父范围

javascript - cavsTxt.measureText 根据字体系列和字体大小为文本提供不同的宽度

javascript - 通过 jQuery 以编程方式设置滚动时不要阻止滚动动画

javascript - 使用分类 ("active"鼠标悬停时 D3 颜色变化,真)

javascript - 将对象 ID 传递到 session 存储

javascript - 如何为动态聊天室配置 Autobahn(crossbar.io)?

Javascript由两个子类继承