0

I want to split basic mathematical operators from a formula string and get operands, I am using the following regex:

(/[+,-,*,/]/g)

It is working fine with + , / and * but not with -.

Sample input 1: "a+b".split(/[+,-,*,/]/g) .
Sample output 1: ["a","b"] //Works fine

Sample input 2: "a-b".split(/[+,-,*,/]/g) .
Sample output 2: ["a-b"] //Not working fine :( should return ["a", "b"], but returns ["a-b"]

I would love to know what I am missing in my expression.
I have an alternative i.e. iterate the whole string and returns a new array without operators but I want to use regex.

Thanks

haMzox
  • 2,073
  • 1
  • 12
  • 25
  • 2
    Use `/[+*\/-]/`, remember to always keep the `-` at the start/end of the character class. Putting `-` at the start of the character class works in all regex flavors I know of. – Wiktor Stribiżew Mar 25 '19 at 08:11
  • 4
    You don't need `,` between characters within brackets. – Seblor Mar 25 '19 at 08:11
  • try this "a-b".split(/[+,\-/,*,/]/g) – Sameer Mar 25 '19 at 08:13
  • 2
    @Sameer ***do not use `,` in the character class***. It doesn't enumerate all possibilities, it means "include `,` in the list of things matched by this character class". – VLAZ Mar 25 '19 at 08:16

0 Answers0