Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart - Split String by RegEx

Tags:

regex

dart

lex

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

like image 723
OhMad Avatar asked Jun 24 '26 15:06

OhMad


1 Answers

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.
like image 129
Kobi Avatar answered Jun 27 '26 09:06

Kobi