'How to match different scenarios with regex in c# and groups

I want to match these different scenarios with a regex pattern. Mainly delimiter is #:

  • 1234-1111-234.011#333 => [id = 1234-1111-234.011 and code =333]
  • whatever text before 1234-1111-234.011#333 => [textb=whatever text before, id = 1234-1111-234.011 , code =333, texta="]
  • 1234-1111-234.011#333 whatever text after => [ textb="" id = 1234-1111-234.011 ,code =333 , texta=whatever text after]
  • Text can be both at the beginning or the end
  • In every case code can contain also a postfix letter W like 1234-1111-234.011#333W => code=333E
  • textb = text with length maximum 15 characters. Only letters and numbers.
  • id = 17 character long with this format XXXX-XXXX-XXX.XXX code - 3 or 4 character long based on W letter is presenting or not
  • texta = text with length maximum 15 characters. Only letters and
    numbers.

I am trying to match these scenarios with this piece of code and groups

pattern ="
    ?(<textb>[\w\s]{15})#
    ?(<id>[\d\s]{17,17})#
    (?<code>([A-Z]{0,1}\d{2,3}))
    (?<wo>[W]{1})
    ?(<texta>[\w\s]{15})"

and

  var textb = Regex.Match(mytext, pattern).Groups["textb"].Value;    
  var id= Regex.Match(mytext, pattern).Groups["id"].Value;
  var code= Regex.Match(mytext, pattern).Groups["code"].Value;
  var wo= Regex.Match(mytext, pattern).Groups["wo"].Value;
  var texta= Regex.Match(mytext, pattern).Groups["texta"].Value;

A full example is "This is before text 234-1111-234.011#333E This is next text"
Not matching at all.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source