如何创建仅接受特殊公式的正则表达式
正则表达式是包含各种字符的模式。我们可以使用正则表达式来搜索一个字符串是否包含特定的模式。
在这里,我们将学习如何创建一个正则表达式来验证各种数学公式。我们将使用test()或match()方法来检查特定的数学公式是否与正则表达式匹配。
语法
用户可以按照以下语法创建接受特殊数学公式的正则表达式。
let regex = /^\d+([-+]\d+)*$/g;
上述的正则表达式只接受10 – 13 + 12 + 23这样的数学公式。
正则表达式解释
/ /- 它表示正则表达式的开始和结尾。-
^- 它表示公式字符串的开始。 -
\d+- 它表示公式开头至少包含一个或多个数字。 -
[-+]- 它表示正则表达式中的’+’和’-‘操作符。 -
([-+]\d+)*- 它表示公式可以多次包含数字后跟’+’或’-‘操作符。 -
$- 它表示字符串的结束。 -
g- 这是用于匹配所有出现的标识符。
示例
在下面的示例中,我们创建了接受包含’+’或’-‘操作符和数字的公式的正则表达式。
用户可以观察到第一个公式与正则表达式模式匹配。第二个公式与正则表达式模式不匹配,因为它包含’*’操作符。另外,第三个公式与第一个公式相同,但是它在操作符和数字之间包含了空格,因此与正则表达式不匹配。
<html>
<body>
<h3>Creating the regular expression to validate special mathematical formula in JavaScript</h3>
<div id = "output"></div>
<script>
let output = document.getElementById('output');
function matchFormula(formula) {
let regex = /^\d+([-+]\d+)*$/g;
let isMatch = regex.test(formula);
if (isMatch) {
output.innerHTML += "The " + formula + " is matching with " + regex + "<br>";
} else {
output.innerHTML += "The " + formula + " is not matching with " + regex + "<br>";
}
}
let formula = "10+20-30-50";
matchFormula(formula);
matchFormula("60*70*80");
matchFormula("10 + 20 - 30 - 50")
</script>
</body>
</html>
在下面的示例中使用的正则表达式
在下面的示例中,我们使用了 /^\d+(\s[-+/]\s\d+)$/g 的正则表达式。用户可以在下面找到使用的正则表达式的解释。
^\d+- 它表示公式开头至少有一位数字。-
\s*- 它表示零个或多个空格。 -
(\s*[-+*/]\s*\d+)*- 它表示公式可以按相同顺序多次包含空格、运算符、空格和数字。
示例
在下面的示例中,我们通过参数传递了各种公式,调用了TestMultiplyFormula()函数三次。我们使用test()方法来检查公式是否与正则表达式模式匹配。
在输出中,我们可以看到正则表达式接受了带有 “*” 和 “/” 运算符和空格的公式。
<html>
<body>
<h2>Creating the regular expression <i> to validate special mathematical formula </i> in JavaScript.</h2>
<div id = "output"> </div>
<script>
let output = document.getElementById('output');
function TestMultiplyFormula(formula) {
let regex = /^\d+(\s*[-+*/]\s*\d+)*$/g;
let isMatch = regex.test(formula);
if (isMatch) {
output.innerHTML += "The " + formula + " is matching with " + regex + "<br>";
} else {
output.innerHTML += "The " + formula + " is not matching with " + regex + "<br>";
}
}
let formula = "12312323+454+ 565 - 09 * 23";
TestMultiplyFormula(formula);
TestMultiplyFormula("41*14* 90 *80* 70 + 90");
TestMultiplyFormula("41*14& 90 ^80* 70 + 90");
</script>
</body>
</html>
这个教程教我们如何创建一个接受特殊数学公式的正则表达式。在两个示例中,我们使用了test()方法来匹配公式和正则表达式。同时,我们在两个示例中使用了不同的正则表达式模式。
极客笔记