M
M
Michael2021-08-26 11:42:01
JavaScript
Michael, 2021-08-26 11:42:01

Specify math example pattern via regular expressions?

There is a prompt, a mathematical example is given as input, which is then converted to a string.
I want to check its validity based on a regular expression

The expression should be something like this:

/a number of 1 or more digits [math options (*+-/)] another number/

So far the

code

try {
  let primer = prompt('Введите пример', '10+2');
  let strPrim = primer.toString();
  let reg = /\d+[\+\-\/\*]\d+/;
  // let reg = /([1-9][0-9]+)(\[\+-\/\*])(\d+)/;
  let primArr = strPrim.split(reg);
  console.log(primArr);
} catch (er) {
  alert('Ошибка: ' + er.name + '. ' + er.message + '/n' + er.stack);
}


Outputs in the console
["NaN"]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Viktor Taran, 2021-08-26
@Misha5

[0-9]{1,} -number from 1 option
[0-9]{1,3} -number from 1 to 3 cir
(\*|\+|\-|\/) or or or, moreover and shielded.
https://regex101.com/r/2PbFdq/1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question