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, @"(\+)");

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

The capture group is not necessary here?
@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: stackoverflow.com/a/2485044/59111
Ty I will be trying this out when I get a chance tonight. Most likely will work. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.