posts - 22, comments - 29, trackbacks - 0

My Links

News

Twitter












Archives

Post Categories

Capturing optional groups in regular expressions?

  string input = @"cool  man dog no dude yes fight son";
  string pattern = @"cool (?<hello>((.)* ))   (?<h>( (dude)?)) (?(h)(?<dude>((.)*)))";
            
       MatchCollection matches = Regex.Matches(input, pattern, RegexOptions.ExplicitCapture
              | RegexOptions.IgnorePatternWhitespace);


            foreach (Match match in matches)
            {
                Console.WriteLine("dude=" + match.Groups["dude"].Value);
                Console.WriteLine("hello=" + match.Groups["hello"].Value);
                Console.ReadLine();
            }
/*Output-


dude=
hello=  man dog no dude yes fight son

*/

But the required output is:

/*Output-


dude=yes fight son
hello=  man dog no

*/


The target is that i want to capture "strings that have cool as first 'word'  and have 'dude' word as optional in between".
Now,I want string that follows word "cool" ("man dog no") until "dude" word comes or end comes.
if "dude" word comes,I want the string that follows word "dude".

Can anybody explain me why the output is not correct or where i am wrong?
Thanks in advance.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Print | posted on Thursday, December 24, 2009 7:05 AM | Filed Under [ .Net Fun C# ]

Feedback

Gravatar

# re: Capturing optional groups in regular expressions?

Hi Sonam,

may I suggest you the following Regex pattern:

@"cool\s+(.*)dude?(.*)|@"cool\s+(.*)

This pattern matches such input text as:
1)@"cool man dog no dude yes fight son"; or
2)@"cool man dog no ";

In case 1) you have to extract the thirst and second groups
In case 2) it will be the 3rd group.

Hope this could help you.

Best regards.
Larissa


12/25/2009 5:40 AM | Larissa
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: