0

To test which mathematical operator (*, /, +, -) exists in the following items:

13*4
7+8
-15/3
7-5

I have the following regex for JavaScript:

/[\*\+/\-]/

The problem is that regex will identify the negative sign in -15/3 as an operator. How do I make it NOT match on first character in the string?

3
  • 1
    also, this is a valid statement 5--5. Commented Sep 4, 2013 at 7:48
  • Eish, getting complicated... but true. Any ideas on how to solve the problem? Commented Sep 4, 2013 at 7:50
  • if you can add spaces before and after operators then this will be simple Commented Sep 4, 2013 at 7:51

3 Answers 3

1

You can match a regex like this:

One or more digits (also allowing a decimal)
followed by optional whitespace 
followed by an operator 
followed by optional whitespace 
followed by one or more digits (also allowing a decimal)

and then reference the captured group in the middle to get just the operator:

/[\d.]+\s*([*+\-\/])\s*[\d.]+/

Sample code:

var match = str.match(/[\d.]+\s*([*+\-\/])\s*[\d.]+/);
if (match) {
    var operator = match[1];
}

Working demo and test code: http://jsfiddle.net/jfriend00/DgrSg/


If you want to allow more than just digits before the operators (such as other expressions), then you will have to do a lot more than a simple or even complex regex. This answer assumes you're just trying to solve the examples that you've presented.

Sign up to request clarification or add additional context in comments.

Comments

1

You could use:

/.[\*\+/\-]/

which just ensures there's a character in front of the symbol.

That's a pretty quick and dirty fix, I'd probably prefer to make a full expression evaluator to catch the hundred other potential error conditions but it'll do if you want something simple and only marginally more robust than what you have.

2 Comments

From what I understand, the . means any character. Is it possible to limit the leading character to a number by simply using //d[\*\+/\-]/ ?
@Jimbo, yes, though it's \d rather than /d. But you should really consider the idea of a proper expression evaluator since a regex doesn't give you the full power - there'll almost always be more edge cases you have to worry about :-)
0

Check that your operator is preceded by a digit and followed by either a digit or a minus sign and a digit.

/\d[\*\+/\-]-?\d/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.