繁体   English   中英

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

[英]JavaScript Regex to match math expression

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

let j = numberArray.join("").match(/^([\\d]*\\.{1,}[\\d]+|[\\d]+)|([-+*/](?=\\.|[\\d]))|\\.[\\d]+|[\\d]+/g);

这是我需要匹配的标准:

  1. 一个数字不能有多个小数。 例如,仅允许使用.1231.123类的数字,但不允许使用...331.2.3.3
  2. 一个运算符不能跟随一个或多个其他运算符。 因此,用户无法连续输入+后跟*

输入示例如下:

输入: ..123+*/.4.3.5-+..3+123

将产生输出: .123/.435+.3+123

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

逻辑很可能会更容易,如果你单独进行这些操作-先用多个小数找到号码,并修复它们,所以它们只包含小数点后第一位, 然后找出重复的运营商,并与最终的运营商替换它们:

 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')); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM