Regex for splitting string into a collection of two based on a pattern

Viewed 235

Using the C# Regex.Split method, I would like to split strings that will always start with RepXYZ, Where the XYZ bit is a number that will always have either 3 or 4 characters.

Examples

  1. "Rep1007$chkCheckBox"
  2. "Rep127_Group_Text"

The results should be:

  1. {"Rep1007","$chkCheckBox"}
  2. {"Rep127","_Group_Text"}

So far I have tried (Rep)[\d]{3,4} and ((Rep)[\d]{3,4})+ but both of those are giving me unwanted results

2 Answers

Using Regex.Split often results in empty or unwanted items in the resulting array. Using (Rep)[\d]{3,4} in Regex.Split, will put Rep without the numbers into the resulting array. (Rep[\d]{3,4}) will put the Rep and the numbers into the result, but since the match is at the start, there will be an empty item in the array.

I suggest using Regex.Match here:

var match = Regex.Match(text, @"^(Rep\d+)(.*)$");
if (match.Success)
{
    Console.WriteLine(match.Groups[1].Value);
    Console.WriteLine(match.Groups[2].Value);
}

See the regex demo

enter image description here

Details:

  • ^ - start of string
  • (Rep\d+) - capturing group 1: Rep and any one or more digits
  • (.*) - capturing group 2: any one or more chars other than a newline, as many as possible
  • $ - end of string.

A splitting approach is better implemented with a lookaround-based regex:

var results = Regex.Split(text, @"(?<=^Rep\d+)(?=[$_])");

See this regex demo.

(?<=^Rep\d+)(?=[$_]) splits a string at the location that is immediately preceded with Rep and one or more digits at the start of the string, and immediately followed with $ or _.

Try splitting on the regex pattern on either $ or _:

string input = "Rep127_Group_Text";
string[] parts = input.Split(new[] { '$', '_' }, 2);
foreach (string part in parts)
{
    Console.WriteLine(part);
}

This prints:

Rep127
Group_Text
Related