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]/
\bImmediately 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-orimmediately preceded with a word char.
