Is there a way to use Regex to split I[1,2]?

Viewed 51

I am extracting a string from an XML file in C# and need the second number in "I[1,2]" which would be 2.

  Regex regex = new Regex(@"\[.*?\]");
  MatchCollection matches = regex.Matches(inputChannel.Value);

  var result = matches[0].Value.Split().Where(x => x.StartsWith("[") && x.EndsWith("]"))
                 .Select(x => x.Replace("[", string.Empty).Replace("]", string.Empty))
                 .ToList();

where inputChannel.value = "I[1;2]"

This code gets the two numbers and sticks them into a list but is there a way to split the two numbers and put them into a list?

1 Answers

Instead of using split, you can use a capture group to get the second number.

I\[[0-9]+;([0-9]+)]
  • I\[ Match I[
  • [0-9]+; Match 1+ digits 0-9 and ;
  • ([0-9]+) Capture group 1, match 1+ digits 0-9
  • ] Match a ] char

See a regex demo.

string pattern = @"I\[[0-9]+;([0-9]+)]";
string input = @"I[1;2]";        
Match m = Regex.Match(input, pattern); 
Console.WriteLine(m.Groups[1].Value); // 2

Or using lookarounds:

(?<=I\[[0-9]+;)[0-9]+(?=])
  • (?<=I\[[0-9]+;) Positive lookbehind, assert I[, 1+ digits followed by ; to the left
  • [0-9]+ Match 1+ digits 0-9
  • (?=]) Positive lookahead, assert ] to the right

See another regex demo.

string pattern = @"(?<=I\[[0-9]+;)[0-9]+(?=])";
string input = @"I[1;2]";        
Match m = Regex.Match(input, pattern); 
Console.WriteLine(m.Value); // 2
Related