Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex.Split command in c#

Tags:

string

c#

regex

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, @"(\+)");
like image 320
Stc5097 Avatar asked Oct 21 '22 13:10

Stc5097


1 Answers

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.

like image 56
Ahmad Mageed Avatar answered Oct 23 '22 02:10

Ahmad Mageed