how to get a text which is starting with 1-3 and having 4 digits after that and Then space and E and 6 digits in .net using Regex

regex [1-3][0-9]{4}(?: E[0-9]{6})?$

sample data
    successful my registration id is #12345 E112233 (should match)
    Successful my data is #22331 E001122          (should match)
    failing    12345                             (should not match)

Expected OP

12345 E112233

22331 E001122

code –

var content ="successful my registration id is #12345 E112233
Successful my data is #22331 E001122          
failing    12345";

       var regex = new Regex(@"[1-3]\d{4}([ ]E\d{6})?$",RegexOptions.Multiline);
       var REG_ID = regex.Match(myStringData).Value;

>Solution :

You can use

var REG_ID = Regex.Match(myStringData, @"#([1-3]\d{4}(?: E\d{6})?)$")?.Groups[1].Value;
// OR - if you use a lookbehind
var REG_ID = Regex.Match(myStringData, @"(?<=#)[1-3]\d{4}(?: E\d{6})?$")?.Value;

See the regex demo.

Pattern details

  • # – find # first ((?<=#) finds a location that is immediately preceded with a # char)
  • ([1-3]\d{4}(?: E\d{6})?) – then capture (into Group 1):
    • [1-3]\d{4} – a 1/2/3 digit + four digits
    • (?: E\d{6})? – an optional sequence of a space + E + six digits
  • $ – end of string.

Leave a Reply