8

I am trying to split a string like this:

x^-5 - 3

into a list like this:

[x^-5, -, 3]

The first minus after the ^ must be at the same list index as the x, because it's just the negative exponent. However, I want other minuses, which are not an exponent of anything, to be on their own index.

When splitting by -, obviously my x^-5 gets split into two as well.

So is there any way I can achieve this using RegEx or something like that?

Thanks in advance

4
  • 6
    Did you try splitting with whitespace? .split(new RegExp(r"\s+")) Commented Apr 26, 2017 at 11:43
  • Sorry, I forgot to mention that it should work without whitespace... But If I don't find another solution, I'll stick to whitespace, thanks. Commented Apr 26, 2017 at 11:50
  • 1
    It turns out, in Dart, you cannot use a JS approach to capture subpatterns to return with the split chunks. You'd better write a parser or use any ready-made libraries. Commented Apr 26, 2017 at 11:56
  • Okay, thank you :) Commented Apr 26, 2017 at 12:04

1 Answer 1

8

If you use allMatches instead of split, you can use a pattern like this:

(?:\^\s*-|[^\-])+|-

Working example: DartPad

  • We match tokens that consist of anything except -, or ^-.
  • If we reach a - that is not an exponent, we match it alone, similar to a split.

Some notes:

  • There are similar patterns, this may not be the most efficient, but it is short.
  • If you are matching mathematical expressions, there are many things that can go wrong (for example parentheses), regular expressions are not a good way to achieve that.
  • This is basically the match to skip trick.
Sign up to request clarification or add additional context in comments.

6 Comments

In other languages you could've used a lookbehind, (?<!\^)-, but that isn't supported on JavaScript (and Dart).
Wow, awesome. Exactly what I was looking for, thank you :)
Btw what would you use instead of regex?
@Rechunk - For example, in JavaScript, I found a library called Math.js, that can parse expressions: mathjs.org/docs/expressions/parsing.html#parse . For Dart, there's this: Is there a math parser for petitparser?, and math_expressions (beta)
how would I extend this regex to be able to split something like this: x^-5 + 3 (with a plus) into this: [x^-5, +, 3]?
|

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.