开发者

how to match this Regular Expressions in javascript

i'm trying to find a way to match this problem but i'm LOST

i want it to match a math 开发者_如何学运维equation that will accept string if:

  • "+-*/%" at anywhere in the string but not in the last character of the input string
  • it accepts float and integers
  • it doesn't accepts letters just numbers and signs

any help ?

Thanks in advance !!


The regular expression you're after looks something like:

-?\d+(?:\.\d+)?([*/%+-]-?\d+(?:\.\d+)?)+

Basically this means:

NUMBER (OPER NUMBER)*

A number is defined as:

  • Optional minus sign;
  • One or more digits;
  • Optionally a period followed by one or more digits.

Now the leading optional minus is not strictly in your requirements so you can safely drop it but without it you can't recognize:

-3*-4

which violates your condition of two operands together. To drop it just drop -? from the expression (in both places) ie:

\d+(?:\.\d+)?([*/%+-]\d+(?:\.\d+)?)+

It's also not clear if you want to accept many operands or just one. If it's just one then:

-?\d+(?:\.\d+)?[*/%+-]-?\d+(?:\.\d+)?

or

\d+(?:\.\d+)?[*/%+-]\d+(?:\.\d+)?

or a variant allowing spaces (\s). You will probably also want to capture the groups using parentheses.

You may want to alter that definition.

Also you could consider allowing spaces between numbers and operands.

An example of usage:

var s = "-11.32 * -34";
var r = /(-?\d+(?:\.\d+)?)\s*([*/%+-])\s*(-?\d+(?:\.\d+)?)/;
var m = r.exec(s);
if (m != null) {
  alert("First: " + m[1] + "\nOperand: " + m[2] + "\nSecond: " + m[3]);
} else {
  alert("Not found");
}


EDITED to answer the modified question.

  • digit: [0-9]
  • number: [0-9]+
  • number with optional decimal portion: [0-9]+(?:\.[0-9]+)?
  • one of those numbers optionally preceded by an operation:
    ([-+/%*])?([0-9]+(?:\.[0-9]+)?)
  • one of the above, followed by zero or more operation+numbber pairs :
    ([-+/%*])?([0-9]+(?:\.[0-9]+)?)(([-+/%*])([0-9]+(?:\.[0-9]+)?))*

This isn't really an equation because there's no = sign.

And you can replace [0-9] with \d in any of the above. I have a habit of specifying the range explicitly, because emacs doesn't do \d.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜