2013-09-26 150 views
1

我试图从这个VMG文件中获取消息字符串。我只希望在日线之后和在字符串 “END:VBODY”2个字符串之间的字符串正则表达式c#

我迄今为止最好的是这个表达式字符串开头:VBODY([^ \ n] * \ n +)+ END:VBODY

任何人都可以帮助完善它?

N: 
TEL:+65123345 
END:VCARD 
BEGIN:VENV 
BEGIN:VBODY 
Date:8/11/2013 11:59:00 PM 
thi is a test message 
Hello this is a test message on line 2 
END:VBODY 
END:VENV 
END:VENV 
END:VMSG 
+1

我不认为你需要使用正则表达式。在BEGIN之后收集任何行很简单:VBODY被看到,直到行结束为止:VBODY – Spaceghost

+0

嘿Spaceghost,你有什么样的c#代码样本会是什么样子 – d123

回答

1

如果你想使用正则表达式,你可以稍微修改你当前的正则表达式,因为$ 0组具有你正在寻找的东西。

BEGIN:VBODY\n?((?:[^\n]*\n+)+?)END:VBODY 

基本上发生了什么事([^\n]*\n+)+变成(?:[^\n]*\n+)+?(把这个部分懒惰可能是更安全)

然后环绕括号是整体的一部分:((?[^\n]*\n+)+?)

我加入\n?在此之前,使输出一点清洁剂。


非正则表达式的解决方案可能是这样的:

string str = @"N: 
    TEL:+65123345 
    END:VCARD 
    BEGIN:VENV 
    BEGIN:VBODY 
    Date:8/11/2013 11:59:00 PM 
    thi is a test message 
    Hello this is a test message on line 2 
    END:VBODY 
    END:VENV 
    END:VENV 
    END:VMSG"; 

int startId = str.IndexOf("BEGIN:VBODY")+11; // 11 is the length of "BEGIN:VBODY" 
int endId = str.IndexOf("END:VBODY"); 
string result = str.Substring(startId, endId-startId); 
Console.WriteLine(result); 

输出:

Date:8/11/2013 11:59:00 PM 
thi is a test message 
Hello this is a test message on line 2 

ideone demo

0

下面是使用正则表达式的解决方案,

 string text = @"N: 
     TEL:+65123345 
     END:VCARD 
     BEGIN:VENV 
     BEGIN:VBODY 
     Date:8/11/2013 11:59:00 PM 
     thi is a test message 
     Hello this is a test message on line 2 
     END:VBODY 
     END:VENV 
     END:VENV 
     END:VMSG"; 


string pattern = @"BEGIN:VBODY(?<Value>[a-zA-Z0-9\r\n.\S\s ]*)END:VBODY";//Pattern to match text. 
Regex rgx = new Regex(pattern, RegexOptions.Multiline);//Initialize a new Regex class with the above pattern. 
Match match = rgx.Match(text);//Capture any matches. 
if (match.Success)//If a match is found. 
{ 
     string value2 = match.Groups["Value"].Value;//Capture match value. 
     MessageBox.Show(value2); 
} 

演示here

现在一个非正则表达式溶液,

 string text = @"N: 
     TEL:+65123345 
     END:VCARD 
     BEGIN:VENV 
     BEGIN:VBODY 
     Date:8/11/2013 11:59:00 PM 
     thi is a test message 
     Hello this is a test message on line 2 
     END:VBODY 
     END:VENV 
     END:VENV 
     END:VMSG"; 

     int startindex = text.IndexOf("BEGIN:VBODY") + ("BEGIN:VBODY").Length;//The just start index of Date... 
     int length = text.IndexOf("END:VBODY") - startindex;//Length of text till END... 
     if (startindex >= 0 && length >= 1) 
     { 
      string value = text.Substring(startindex, length);//This is the text you need. 
      MessageBox.Show(value); 
     } 
     else 
     { 
      MessageBox.Show("No match found."); 
     } 

演示here

希望它有帮助。

相关问题