2017-06-18 51 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。否则,只需分割分号。