2013-09-26 148 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

希望它有幫助。

相關問題