2016-11-24 28 views
1

我正在尋找一種方式,正則表達式內忽略的話只匹配,如果這個詞是不是{C} {文/ 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 @@[email protected]@*/ 
/{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

正則表達式是不很適合於處理這樣的嵌套構建體。 – 2016-11-24 05:02:36

+0

你能告訴我其他可能的解決方案嗎? Regexp是我做這類工作時唯一知道的事情。 – Yanaro

+0

我們也可以用純javascript來做 –

回答

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);

+0

如果{c}塊位於另一個{c}塊內,但是如果另一個塊像{c} {q} {/ q} {/ c} – Yanaro

+0

對不起,沒有得到你。你可以評論上例的例子輸入和輸出嗎? –

+0

看到我編輯的問題。我使用{q}來解析blockquote,{c}解析預覽。當我輸入時,{c} {q} {/ q} {/ c},我得到

,但我希望它是
{q} {/q}
Yanaro

相關問題