Reputation: 1524
I am trying to parse a line of code for a mathematical operation.
Such as: 4+18/(9-3)
I want the sections to be: 4, +, 18, /, (, 9, -, 3, and ). So basically, all numbers, operators, and parenthesis.
If I use split with delimiters it removes the delimiter upon finding it. So if I use my operators as delimiters, well then they're removed.
I tried using Regex.split and it INCLUDES the operator, but not how I want it. It produces results like 4+, since it includes the 4 and the plus.
Here's what I've been trying:
string convert = "4+8/(9-3)";
string[] parts = Regex.Split(convert, @"(?<=[-+*/])");
Upvotes: 2
Views: 99
Reputation: 2482
As per my comment if you intend to use this to evaluate a math expression you should not use Regex as you cannot have any syntactic or semantic understanding of a string you're parsing.
If you're not intending to do that, this should work fine
([\d\.]+|[()e^/%x*+-])
Upvotes: 4
Reputation: 18997
Well, I guess the problem could be solved with the help of the following regex.
[-+*/\(\)]|\d+
Upvotes: -1