Home > database >  C# Regex - Extract multiple parts of string
C# Regex - Extract multiple parts of string

Time:09-01

In C#, I am trying to extract multiple parts (in bold & italic) of string which would be in below format. Note thats numbers could be 6-7 digits longer so don't need any restriction on length however first part of string in bold italic would always be 3 char long.

TCS-TST.MSL-M365-SPO.S8629-O2887.Engagement

At the moment I am using string.Split() which requires splitting string multiple times and extracting the part I need. So was wondering if there's better way to do it using REGEX.

CodePudding user response:

Try some online tools.

^\w{3}-(?<First>\w{3}).\w{3}-\w\d -\w{3}.\w(?<Second>\d )-\w(?<Third>\d ).\w $

This is a good start, then use group names to extract values:

var regex = new Regex(@"^\w{3}-(?<First>\w{3}).\w{3}-\w\d -\w{3}.\w(?<Second>\d )-\w(?<Third>\d ).\w $");
var match = regex.Match(input);
if (!match.Success)
    return;

var first = match.Groups["First"];
var second = match.Groups["Second"];
var third = match.Groups["Third"];
  • Related