Home > Software engineering >  JavaScript regex get - * / after a number
JavaScript regex get - * / after a number

Time:10-28

Hey I want to make a simple calculator. The calculator should do negatives and so I want to split my input string where I match a " - * /"

Input is for example "5 -3" so I want to match only the " " because the "-" is part of my second number "-3"

The regex that I have at the moment is:

/(\ |-|\*|\)/

But this gives me the " " and "-"

CodePudding user response:

I think this might work:

/(?<=[0-9] )[ \-*/](?=-?[0-9] )/
  • (?<=[0-9] ) is a "positive lookbehind": it means it checks that the expression between (?<= and ) precedes the main expression but it is not matched. In this case we are checking that there is one or more digits ([0-9] ) before the operator
  • [ \-*/] matches any of the four operators , -, * and /
  • (?=-?[0-9] ) is a "positive lookahead": it means it checks that the expression between (?= and ) follows the main expression but it is not matched. In this case we are checking that there is an optional minus sign (-?) followed by one or more digits ([0-9] ) after the operator

IMPORTANT: some browsers might not support the the positive lookbehind feature

CodePudding user response:

Borrowing @Viktor's insight of using a word-boundary...

/\b[^.\d]/
  • \b Immediately following an alphanumeric (which excludes ,-,/,*).

  • [^.\d] Split on a single character that is not a period or decimal.

CodePudding user response:

You can use

/([*\/]|\b[- ])/

See the regex demo.

The [*\/]|\b[- ] pattern matches either

  • [*\/] - a * or / char
  • | - or
  • \b[- ] - a - or immediately preceded with a word char.
  • Related