Open In App

How to create regular expression only accept special formula ?

In this article, you will understand the use of regular expressions to accept special formulas. Here we will start by understanding to use Regular Expressions in Javascript and later we will understand to create the pattern for the special formulas. Regular expressions are patterns used to match character combinations in strings.

Example 1: This expression accepts the words and spaces.



\w+\s

Example 2: This expression accepts the digits of length 1 or more.

\d+

More about Regular expressions here.



We can construct a regular expression in one of two ways:

const re = /a+b/;
const re = new RegExp('a+b');

Regular Expression for special formula: The special formula consists of operands and operators.

Syntax:

formula = operand operator operand

where,

General Regular Expression for this looks like this:

digit (operand digit)*

where,

We will make use of Javascript RegExp, character classes, and quantifiers to specify the formula. Let’s first understand them in brief.

1. Javascript RegExp: This is the data type in javascript used to create Regular expressions.

Syntax:

var RE = /pattern/flags

where,

2. Quantifier: It indicates the number of characters to match.

Syntax:

n+ = one or more
n* = zero or more

3. Character Classes: These indicate kinds of characters like digits or letters.

Syntax:

\d : digit
\D : non-digit
\w : alphabet
\W : non-alphabet

Steps to create regular expression only accept the special formula

To accept a formula let’s say for example 4-3+2+1, you can use an expression ^\d+([+-]\d+)*$ in Javascript.

where,

Example 1: Let us implement the expression 4-3+2+1 in javascript using the test() method.




<script>
const re = /^\d+([+-]\d+)*$/g;
console.log(re.test("4-3+2+1"));
</script>

Output:

true

Example 2: Let us implement the expression 4*5-3/2 in javascript using the test() method by including the * and / operators.




<script>
const re = /^\d+(?:[-+*/^]\d+)*$/g;
console.log(re.test("4*5-3/2"));
</script>

Output:

true

Example 3: Invalid match for example 1




<script>
const re = /^\d+([+-]\d+)*$/g;
console.log(re.test("4-3*1/2"));
</script>

Output:

false

Article Tags :