Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Regex, Either Or

Tags:

c#

regex

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 
like image 840
Mark Avatar asked Mar 03 '26 07:03

Mark


1 Answers

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();
        }
    }
}
like image 160
Jon Skeet Avatar answered Mar 05 '26 19:03

Jon Skeet