5

I am trying to use Regex.SPlit to split a a string in order to keep all of its contents, including the delimiters i use. The string is a math problem. For example, 5+9/2*1-1. I have it working if the string contains a + sign but I don't know how to add more then one to the delimiter list. I have looked online at multiple pages but everything I try gives me errors. Here is the code for the Regex.Split line I have: (It works for the plus, Now i need it to also do -,*, and /.

string[] everything = Regex.Split(inputBox.Text, @"(\+)");
Matt Tester
  • 4,663
  • 4
  • 29
  • 32
Stc5097
  • 291
  • 1
  • 11
  • 25

1 Answers1

3

Use a character class to match any of the math operations: [*/+-]

string input = "5+9/2*1-1";
string pattern = @"([*/+-])";
string[] result = Regex.Split(input, pattern);

Be aware that character classes allow ranges, such as [0-9], which matches any digit from 0 up to 9. Therefore, to avoid accidental ranges, you can escape the - or place it at either the beginning or end of the character class.

Ahmad Mageed
  • 94,561
  • 19
  • 163
  • 174
  • The capture group is not necessary here? – hwnd Feb 27 '14 at 03:02
  • @hwnd the capture group is necessary to retain the delimiters as part of the split result, otherwise they would be excluded. I have a related answer here: http://stackoverflow.com/a/2485044/59111 – Ahmad Mageed Feb 27 '14 at 03:05
  • Ty I will be trying this out when I get a chance tonight. Most likely will work. Thank you – Stc5097 Feb 27 '14 at 03:08