2

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, @"(?<=[-+*/])");
Birdman
  • 1,404
  • 5
  • 22
  • 49

2 Answers2

4

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*+-])

Regexr example

Dotnetfiddle example

Prime
  • 2,410
  • 1
  • 20
  • 35
  • @Aran-Fey You're correct, changed from `Regex.Split` to `Regex.Matches` – Prime Apr 01 '18 at 00:12
  • This added some extra "" empty string entries for me but I just created a quick loop to remove them. Not sure if I did something wrong to include them, but once the empty strings were removed which was easy enough the results so far from my testing have been desirable. Thanks. – Birdman Apr 01 '18 at 01:16
  • @Birdman It's because of how `Regex.Split` works, if you check the Dotnetfiddle example I use `Regex.Matches` and loop through the matches it returns instead. – Prime Apr 01 '18 at 01:44
-1

Well, I guess the problem could be solved with the help of the following regex.

[-+*/\(\)]|\d+
nicael
  • 18,550
  • 13
  • 57
  • 90
  • Nope. This splits numbers into single digits. – Aran-Fey Mar 31 '18 at 23:51
  • 1
    Nope. Now it duplicates every character. And even if you change that capture group to a non-capturing group it still would split numbers into single digits. Please test your regex; this is getting silly. – Aran-Fey Mar 31 '18 at 23:55
  • "it still would split numbers into single digits" - how is that, @Aran? – nicael Mar 31 '18 at 23:57
  • Well, because it doesn't matter if you use `\d` or `\d+` in a lookbehind. After the regex passes the first digit, the lookbehind sees a digit and the number is split into two, `+` or not. – Aran-Fey Mar 31 '18 at 23:59
  • @Aran I didnt think of lookbehind but now im actually not sure why op used it all – nicael Apr 01 '18 at 00:03
  • It shouldnt be a problem for it to work without lookbehind unless i am missing something else in the question – nicael Apr 01 '18 at 00:04
  • Now the result is just empty strings. I'm going to bed now and will check back tomorrow morning... – Aran-Fey Apr 01 '18 at 00:05