如何创建只接受特殊公式的正则表达式?

WBOY
WBOY 转载
2023-09-16 19:33:03 732浏览

如何创建只接受特殊公式的正则表达式?

正则表达式是包含各种字符的模式。我们可以使用正则表达式来搜索字符串是否包含特定模式。

在这里,我们将学习创建正则表达式来验证各种数学公式。我们将使用 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() 方法来将公式与正则表达式进行匹配。此外,我们在两个示例中使用了不同的正则表达式模式。

以上就是如何创建只接受特殊公式的正则表达式?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除