-3

Techies,

I'm working on kind of calculator, am not much comfortable with regex. My need is JavaScript regular expression to validate whether both ( ) brackets are present, there may be some character inside the brackets.

suggestions please

Arun
  • 37
  • 8

2 Answers2

0

Simple regex:

var string = '1234 + 1234 (5)';
if (string.match('\(|\)')) {
    console.log('() found')
}
Tony Stark
  • 330
  • 3
  • 12
0

Simply matching

\(.*\)

will match if both an opening, and a closing parentheses are present. (Parentheses need to be escaped since it's a special character in regex.) .* matches anything, including an empty string.

But I assume you'd want to allow strings without any parentheses as well. This regex allows for any number of pairs of parentheses (not nested) or none at all:

^[^()]*(?:\([^()]*\)[^()]*)*$

It matches start of string ^, a string of any length not containing parentheses [^()]*. Then any number of the combination 1. Opening P(arentheses) 2. Any length string w/o P's. 3. A closing P. 4. Any length string w/o P's. (Possibly repeated any number of times.) Finally it matches end of string $.

Working example (Type an expression into the input control, and press Enter.):

var inputExpression = document.getElementById("expression");

function testExpression(){
    console.log(inputExpression.value.match(/^[^()]*(?:\([^()]*\)[^()]*)*$/) ? "Well formed" : "Unbalanced parentheses");
//    inputExpression.value = '';
}


inputExpression.addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode === 13) {
        testExpression();
    }
});
Enter an expression:<input id="expression" type="text" onBlur="testExpression()"/>
SamWhan
  • 8,038
  • 1
  • 14
  • 42