How to create regular expression only accept special formula?

Regular expressions are powerful patterns used to validate and match specific text formats. In this tutorial, we'll learn how to create regular expressions that validate mathematical formulas containing various operators and formats.

Basic Formula Validation

Let's start with a simple regular expression that accepts basic mathematical formulas with addition and subtraction operators.

Syntax

let regex = /^\d+([-+]\d+)*$/g;

This regex accepts formulas like "10-13+12+23" with no spaces between operators and numbers.

Regular Expression Breakdown

  • ^ - Represents the start of the string

  • \d+ - Matches one or more digits at the beginning

  • [-+] - Matches either '+' or '-' operators

  • ([-+]\d+)* - Matches zero or more occurrences of operator followed by digits

  • $ - Represents the end of the string

  • g - Global flag to match all occurrences

Example: Basic Addition and Subtraction

<html>
<body>
   <h3>Validating Basic Mathematical Formulas</h3>
   <div id="output"></div>
   <script>
      let output = document.getElementById('output');
      
      function validateBasicFormula(formula) {
         let regex = /^\d+([-+]\d+)*$/g;
         let isMatch = regex.test(formula);
         
         if (isMatch) {
            output.innerHTML += "? '" + formula + "' matches the pattern<br>";
         } else {
            output.innerHTML += "? '" + formula + "' does not match the pattern<br>";
         }
      }
      
      validateBasicFormula("10+20-30-50");     // Valid
      validateBasicFormula("60*70*80");        // Invalid (contains *)
      validateBasicFormula("10 + 20 - 30");    // Invalid (contains spaces)
   </script>
</body>
</html>
? '10+20-30-50' matches the pattern
? '60*70*80' does not match the pattern
? '10 + 20 - 30' does not match the pattern

Advanced Formula with All Operators and Spaces

For more complex formulas that include multiplication, division, and optional whitespace, we use a more comprehensive pattern:

let regex = /^\d+(\s*[-+*/]\s*\d+)*$/g;

Enhanced Pattern Explanation

  • ^\d+ - One or more digits at the start

  • \s* - Zero or more whitespace characters

  • [-+*/] - Matches +, -, *, or / operators

  • (\s*[-+*/]\s*\d+)* - Zero or more occurrences of: optional spaces, operator, optional spaces, and digits

Example: Complete Mathematical Formulas

<html>
<body>
   <h3>Validating Complete Mathematical Formulas</h3>
   <div id="output"></div>
   <script>
      let output = document.getElementById('output');
      
      function validateCompleteFormula(formula) {
         let regex = /^\d+(\s*[-+*/]\s*\d+)*$/g;
         let isMatch = regex.test(formula);
         
         if (isMatch) {
            output.innerHTML += "? '" + formula + "' is a valid formula<br>";
         } else {
            output.innerHTML += "? '" + formula + "' is invalid<br>";
         }
      }
      
      validateCompleteFormula("123 + 454 - 565 * 23");     // Valid
      validateCompleteFormula("41*14* 90 /80* 70 + 90");   // Valid
      validateCompleteFormula("41*14& 90 ^80* 70 + 90");   // Invalid (contains & and ^)
   </script>
</body>
</html>
? '123 + 454 - 565 * 23' is a valid formula
? '41*14* 90 /80* 70 + 90' is a valid formula
? '41*14& 90 ^80* 70 + 90' is invalid

Comparison of Approaches

Pattern Operators Supported Spaces Allowed Use Case
/^\d+([-+]\d+)*$/g + and - only No Basic arithmetic
/^\d+(\s*[-+*/]\s*\d+)*$/g +, -, *, / Yes Complete formulas

Common Use Cases

  • Form Validation - Validating calculator input fields

  • Expression Parsers - Pre-validating mathematical expressions

  • Educational Tools - Checking student math input formats

Conclusion

Regular expressions provide a powerful way to validate mathematical formulas. Use the basic pattern for simple arithmetic and the advanced pattern for comprehensive formula validation including all operators and optional whitespace.

Updated on: 2026-03-15T23:19:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements