Regular Expression Capture groups

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #1

    Regular Expression Capture groups

    I'm having no end of trouble getting a correct regular expression for what I am doing. It probably would have taken me 5mins to produce a plain text matching system with string indexes, but even after an hour of failing, I still want to use regex.

    I have something like the following as input text
    Code:
    #define  HIT_VAL1       4               //  some comment
    #define  HIT_VAL2       5               //  some comment
    #define  HIT_VAL3       6               //  some comment
    And I am looking to pull 2 pieces of information from each line.
    So for the following line, I want the bold parts
    #define HIT_VAL1 4 // some comment
    _______________ ^ not bold


    I have tried various variations on this for just the first bold section:
    Regex rx = new Regex(@"^#defin e HIT_(\w)*", RegexOptions.Ig noreCase);
    or
    Regex rx = new Regex(@"^(?:#de fine HIT_)(\w)*", RegexOptions.Ig noreCase);

    But all I ever get is:
    #define HIT_VAL1
    #define HIT_VAL2
    #define HIT_VAL3

    (?: ) said it should be a NON capture group, I want to ignore that part. I could just pop it off with a string.replace( ) but I still feel regular expressions should be useful for SOMETHING.
    Does anyone have any thoughts? I keep going through regex tutorials, but apparently regex was designed to only do a single match? That seems very poorly thought out?
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    I think I figured it out. Was a problem with how I looked at the matches vs groups.
    Assuming my input string is WholeData, the following worked:
    [code=c#]
    Regex rx = new Regex(@"^#defin e[\s|\t]+(?<preType>\w* )_(?<name>\w*)[\s|\t]+(?<value>\w*)[\s|\t]+//[\s|\t]*(?<comment>.*) ", RegexOptions.Ig noreCase | RegexOptions.Mu ltiline);
    MatchCollection matches = rx.Matches(Whol eData);
    Console.WriteLi ne("MatchesCoun t "+matches.Count );
    foreach (Match m in matches)
    {
    //Console.WriteLi ne("Match: '" + m.Value + "'");
    //Console.WriteLi ne("GroupCount : " + m.Groups.Count) ;
    Console.WriteLi ne("Want name: " + m.Groups["name"].Value);
    Console.WriteLi ne("Want value: " + m.Groups["value"].Value);
    Console.WriteLi ne("Want comment: " + m.Groups["comment"].Value);
    }
    [/code]

    Comment

    Working...