2011-03-31 496 views
1

我怎麼能在C#正則表達式(正則表達式)

I need //cursive// text and //cursive// text. 

INTO替換那些字符串:

I need <i>cursive</i> text and <i>cursive</i> text. 

This si me [website[http://www.website.com]] and other me [website[http://www.website2.com]]. 

分爲:

This si me <a href='http://www.website.com'>website</a> and other me <a href='http://www.website2.com'>website</a>. 

Solutiuon爲第一動作:

string Test = "Mama ma //hodne// prace protoze //neni// doma."; 
string Result = Regex.Replace(Test, "//(.+?)//", "<i>$1</i>"); 

解第二動作:由JinDave發現

string Test2 = "Mama ma [hodne[http://www.someurl.com]] protoze [neni[http://www.someurl.com]] doma."; 
string Result2 = Regex.Replace(Test2, "\\[(.+?)\\[(.+?)\\]\\]", "<a href='$2' target='_blank'>$1</a>"); 
+3

也許你需要使用降價庫:http://stackoverflow.com/questions/888985/what-markdown-c-library-should-i-use? – mlsteeves 2011-03-31 11:33:55

+2

正確的答案是,不要使用正則表達式。使用解析器。請參閱http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – stusmith 2011-03-31 11:35:20

+1

@stusmith:OP想從純文本轉換爲HTML,所以正則表達式可能夠好了。解析器可能也會完成這項工作,而不是HTML解析器。 – LukeH 2011-03-31 11:38:34

回答

0

解決方案:

Solutiuon爲第一動作:

string Test = "Mama ma //hodne// prace protoze //neni// doma."; 
string Result = Regex.Replace(Test, "//(.+?)//", "<i>$1</i>"); 

解決方案第二幕:

string Test2 = "Mama ma [hodne[http://www.someurl.com]] protoze [neni[http://www.someurl.com]] doma."; 
string Result2 = Regex.Replace(Test2, "\\[(.+?)\\[(.+?)\\]\\]", "<a href='$2' target='_blank'>$1</a>"); 
+1

您剛剛從問題中複製瞭解決方案並將其粘貼到此處。 ಠ_ಠ – Kobi 2011-04-04 09:47:08

+0

Yeup!這個問題現在有機會被接受。 – Stephan 2011-04-04 09:50:51

+2

嗯,這就是......不是很順利,在我看來......我鼓勵OP添加一個答案。 – Kobi 2011-04-04 09:54:52