Search code examples
c#regexbnf

Regex for Backus-Naur Form


i'm trying to make a regex to match a string like:

 i<A> | n<B> | <C>

It needs to return the values:

  • ("i", "A")
  • ("n", "B")
  • ("", "C")

Currently i'm using the following regex:

^([A-Za-z0-9]*)\<(.*?)\> 

but it only matches the first pair ("i", "A").

I can't find a way to fix it.


Solution

  • the ^ asserts position at start of a line so it will only check the beginning of each line if you remove that i should work and add a ? for the empty value see example below

    string pattern = @"([A-Za-z0-9]?)<(.?)>";
    string input = @"i<A> | n<B> | <C>";
    RegexOptions options = RegexOptions.Multiline;
    
    foreach (Match m in Regex.Matches(input, pattern, options))
    {
        Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
    }