tags:

views:

44

answers:

1

I have a string that I parse in regex:

"one [two] three [four] five"

I have regex that extracts the bracketed text into <bracket>, but now I want to add the other stuff (one, three, five) into <text>, but I want there to be seperate matches.

So either it is a match for <text> or a match for <bracket>. Is this possible using regex?

So the list of matches would look like:

text=one, bracketed=null 
text=null, bracketed=[two] 
text=three, bracketed=null 
text=one, bracketed=[four]
text=five, bracketed=null 
+2  A: 

Is this what you're after? Basically | is used for alternation in regular expressions.

using System;
using System.Text.RegularExpressions;

public class Test 
{
    public static void Main()
    {
        string test = "one [two] three [four] five";
        Regex regex = new Regex(@"(?<text>[a-z]+)|(?<bracketed>\[[a-z]+\])");

        Match match = regex.Match(test);
        while (match.Success)
        {
            Console.WriteLine("text: {0}; bracketed: {1}",
                              match.Groups["text"],
                              match.Groups["bracketed"]);
            match = match.NextMatch();
        }
    }
}
Jon Skeet
Yep, exactly waht I was after. I can't beleve I overlooked the pipe. THanks for the help.
Mark