2010-05-13 38 views
3

我有類似這樣的文本。在C中的正則表達式#

@@ MMIVLoader @ ProductVer @ 4.1.2 @ BCM_7400S_LE @ @產品2009年8月21日@
@@ MMIVLib @ ObjectVer @ 4.1.2 @ BCM_7400S_LE @ @產品2009年8月21日@
@@ HuaweFGDLDrv @ ObjectVer @ 01.00.09 @ 7324 @ PRODUCT @ Aug 20 2009 @
@@ ProtectVer @ ObjectVer @ 127.8.1 @ BCM_SDE5.03 @ PRODUCT @ Aug 4 2009 06:56:19 @
@@ KernelSw @ ObjectVer @ 0.0 .1 @ BCM-7454 @ PRODUCT @ Dec 19 2007 @
@@ ReceiverSw @ ObjectVer @ E.5.6.001 @ HWBC01ZS @ PRODUCT @ 2010年5月3日@

我想出來放在一個陣列像

MMIVLoader 4.1.2 
MMIVLib   4.1.2 
HuaweFGDLDrv 01.00.09 
ProtectVer 127.8.1 
KernelSw 0.0.1 
ReceiverSw E.5.6.001 

任何一個可以建議我如何使用正則表達式來做到這一點在C#或是否有任何複雜的方式來做到這一點

在此先感謝

回答

8

這很簡單,你可以分開@(刪除空的物品)並拉第一和第三項。

var list = myString.Split(new String[] {Environment.NewLine}, 
      StringSplitOptions.RemoveEmptyEntries)     
    .Select(item => item.Split(new char[] {'@'}, 
      StringSplitOptions.RemoveEmptyEntries)) 
    .Where(a => a.Length > 2) 
    .Select(a => new { Item = a[0], Version = a[2] }).ToArray(); 
+0

美麗。我在考慮拆分它,但額外的@讓我很煩惱。 'RmoveEmptyEntries'是一個不錯的選擇。 – mpen 2010-05-13 07:13:17

+0

我們如何使用正則表達式來做到這一點? – user340015 2010-05-13 07:17:45

+0

我已更新,因此它將在整個字符串上運行。 – cjk 2010-05-13 07:21:14

0

爲了完整起見,這裏是一個LINQ版本查詢語法:)

string[] lines = new string[] { 
      "@@[email protected]@[email protected][email protected]@Aug 21 [email protected]", 
      "@@[email protected]@[email protected][email protected]@Aug 21 [email protected]", 
      "@@[email protected]@[email protected]@[email protected] 20 [email protected]", 
      "@@[email protected]@127.8.1 @[email protected]@Aug 4 2009 06:56:[email protected]", 
      "@@[email protected]@[email protected]@[email protected] Dec 19 [email protected]", 
      "@@[email protected]@[email protected]@[email protected] 3 [email protected]" }; 
var q = from components in 
      (from line in lines 
      select line.Split(new char[] { '@' }, 
        StringSplitOptions.RemoveEmptyEntries)) 
     select new { Name = components[0], Version = components[2] }; 
foreach (var item in q) 
{ 
    Console.WriteLine("Item: Name={0} Version={1}", item.Name, item.Version); 
} 
+0

您知道我的是Linq解決方案嗎? – cjk 2010-05-13 07:21:50

+0

@ck:是的我知道..我的意思是查詢語法。我會換個話 – 2010-05-13 07:25:24

2

如果你想一個瘋狂的正則表達式的解決方案,您可以使用此:

var matches = Regex.Matches(
    input, 
    "@@(?<name>.*?)@(Product|Object)[email protected](?<ver>.*?)@", 
    RegexOptions.IgnoreCase 
).Cast<Match>().Select(m => m.Groups); 

foreach (var match in matches) 
{ 
    Console.WriteLine("{0} {1}", match["name"], match["ver"]); 
} 
3

或者乾脆從行中刪除多餘的東西

Regex.Replace(text, @"^@@([^@]+)@[^@][email protected]([^@]+).*", "$1,$2",RegexOptions.Multiline); 

得到

MMIVLoader,4.1.2 
MMIVLib,4.1.2 
HuaweFGDLDrv,01.00.09 
ProtectVer,127.8.1 
KernelSw,0.0.1 
ReceiverSw,E.5.6.001 

接着,就用逗號分割每行獲得陣列