C# : Regular Expression
        Posted  
        
            by 
                Pramodh
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Pramodh
        
        
        
        Published on 2011-01-02T06:48:20Z
        Indexed on 
            2011/01/02
            6:53 UTC
        
        
        Read the original article
        Hit count: 247
        
I'm having a set of row data as follows
 List<String> l_lstRowData = new List<string> { "Data 1 32:01805043*0FFFFFFF", 
                                                "Data 3, 20.0e-3", 
                                                "Data 2, 1.0e-3 172:?:CRC" ,
                                                "Data 6"
                                              };
and two List namely "KeyList" and "ValueList" like
 List<string> KeyList = new List<string>();
 List<string> ValueList = new List<string>();
I need to fill the two List<String> from the data from l_lstRowData using Pattern Matching
And here is my Pattern for this
 String l_strPattern = @"(?<KEY>(Data|data|DATA)\s[0-9]*[,]?[ ][0-9e.-]*)[ \t\r\n]*(?<Value>[0-9A-Za-z:?*!. \t\r\n\-]*)";
 Regex CompiledPattern=new Regex(l_strPattern,RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
So finally the two Lists will contain
 KeyList 
            { "Data 1" }
            { "Data 3, 20.0e-3" }
            { "Data 2, 1.0e-3" }
            { "Data 6" }
 ValueList 
            { "32:01805043*0FFFFFFF" }
            { "" }
            { "172:?:CRC" }
            { "" }
Scenerio:
The Group KEY in the Pattern Should match "The data followed by an integer value , and the if there exist a comma(,) then the next string i.e a  double value
The Group Value in the Pattern should match string after the whitespace.In the first string it should match 32:01805043*0FFFFFFF but in the 3rd 172:?:CRC.
Here is my sample code
 for (int i = 0; i < l_lstRowData.Count; i++)
        {
            MatchCollection M = CompiledPattern.Matches(l_lstRowData[i], 0);
            KeyList.Add(M[0].Groups["KEY"].Value);
            ValueList.Add(M[0].Groups["Value"].Value);
        }
But my Pattern is not working in this situation.
Please help me to rewrite my Pattern.
© Stack Overflow or respective owner