JavaScript正则表达式以匹配数学表达式

时间:2018-12-09 22:28:23

标签: javascript regex

我需要以下正则表达式的帮助:

VARCHAR

这是我需要匹配的条件:

  1. 一个数字不能有多个小数。例如,仅允许使用诸如let j = numberArray.join("").match(/^([\d]*\.{1,}[\d]+|[\d]+)|([-+*/](?=\.|[\d]))|\.[\d]+|[\d]+/g);.123之类的数字,而不允许使用1.123...33之类的数字。
  2. 一个运算符不能跟随一个或多个其他运算符。因此,用户无法连续输入1.2.3.3后跟+

示例输入和输出:

输入:*

将产生输出:..123+*/.4.3.5-+..3+123

我实际上认为我已经设置了第二个条件(关于运算符),但是我一直在努力使用小数点。我是正则表达式的新手,正在尽力破解这一表达式,但是一段时间后,它就开始流行起来。任何帮助深表感谢!

1 个答案:

答案 0 :(得分:2)

如果您分别进行这些操作 ,则逻辑可能会更容易-首先找到具有多个小数位的数字,然后对其进行修复,使其只包含第一个小数位,然后 找到重复的运算符,然后将其替换为最终运算符:

const clean = str => str
  // Match zero or more digits, followed by a decimal,
  // followed by more digit and decimal characters
  // For everything past the first decimal, replace decimals with the empty string
  .replace(
    /(\d*\.)([\d.]+)/g,
    (_, g1, g2) => g1 + g2.replace(/\./g, '')
  )
  // Match 2 or more operators, capture the last operator in a group
  // Replace with the last operator captured
  .replace(
    /([-+/*]){2,}/g,
    '$1'
  );
  
console.log(clean('..123+*/.4.3.5-+..3+123'));