5

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

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
OhMad
  • 6,871
  • 20
  • 56
  • 85

1 Answers1

6

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.
Community
  • 1
  • 1
Kobi
  • 135,331
  • 41
  • 252
  • 292
  • In other languages you could've used a lookbehind, [`(?<!\^)-`](https://regex101.com/r/2vlDCy/1), but that isn't supported on JavaScript (and Dart). – Kobi Apr 26 '17 at 12:30
  • Wow, awesome. Exactly what I was looking for, thank you :) – OhMad Apr 26 '17 at 12:31
  • Btw what would you use instead of regex? – OhMad Apr 26 '17 at 12:34
  • @Rechunk - For example, in JavaScript, I found a library called Math.js, that can parse expressions: http://mathjs.org/docs/expressions/parsing.html#parse . For Dart, there's this: [Is there a math parser for petitparser?](http://stackoverflow.com/q/18924498/7586), and [math_expressions (beta)](https://pub.dartlang.org/packages/math_expressions) – Kobi Apr 26 '17 at 12:39
  • 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]? – OhMad Apr 26 '17 at 18:36
  • @Rechunk - That's pretty simple. You need to change all places you have `-` to also accept `+`. For example (also with `*` and `/`): `(?:[\^*/]\s*[\-+]|[^\-+])+|[\-+]` - [example](https://regex101.com/r/O2QaDh/1) – Kobi Apr 26 '17 at 18:49