2017-06-18 47 views
-3

什麼是正規表達式模式,以實現以下任務如何使用正則表達式解析數據

數據格式(模式)

anyword:anycharcters;

樣品輸入

msg:"c# 6.0 is good";sid:201;classtype:object oriented;.net,ado.net,other messages 

預期輸出(匹配組)

msg:"c# 6.0 is good"; ----------> 1 
sid:201;--------------------->2 
classtype:object oriented;---------->3 
+0

[String.split](HTTPS://msdn.microsoft.com/en-us/library/system.string.split \(V = vs.110 \ ).aspx)可能比鑽研正則表達式更容易。 –

回答

1
string g = @"msg:""c# 6.0 is good"";sid:201;classtype:object oriented;.net,ado.net,other messages"; 

foreach (Match match in Regex.Matches(g, @"(.*?):([^;]*?;)", RegexOptions.IgnoreCase)) 

Console.WriteLine(match.Groups[1].Value + "--------"+match.Groups[2].Value); 

輸出:

msg--------"c# 6.0 is good"; 
sid--------201; 
classtype--------object oriented; 
1

你並不需要在這裏使用正則表達式匹配。相反,你可以只是嘗試用分號分隔符分割字符串:

string value = "msg:\"c# 6.0 is good\";sid:201;classtype:object oriented;.net,ado.net,other messages"; 
string[] lines = Regex.Split(value, ";"); 

foreach (string line in lines) { 
    Console.WriteLine(line); 
} 

Demo

+1

爲什麼在OP需要正則表達式解決方案時回答命令性代碼?你有沒有想過他可能想學習正則表達式,因此他將這個問題標記爲正則表達式?分裂你不需要Regex.Split。 –

+0

@羅伊你的答案使用覆蓋的匹配器。實際上,我們很可能會用分隔符分隔這裏。 –

+0

OP特意說_(配對組)_。並非所有問題都是XY問題。這可能是一個更復雜問題的簡化。更不用說,它使用正則表達式進行分割的開銷很大。 –

1

如果你真的有利於正則表達式的解決方案,你可以使用:

[^;]+; 
# not a ; 1+ 
# a ; 

a demo on regex101.com。否則,只需分割分號。