skip to Main Content

How do i match a string to a regex pattern in javascript, but the string does not have to follow the serial arrangement in the regex Pattern.
The regex pattern test against a string containing brackets with the conditions that;

  • Open brackets must be closed by the same type of brackets.
  • Open brackets must be closed in the correct order.
  • Every close bracket has a corresponding open bracket of the same type.

This is what i tried;

const pattern = /^(())*({})*([])*$/

if i test it against these strings, it works fine

console.log(pattern.test("(){}[]")) //returns true
console.log(pattern.test("(]") //returns false

but if change the order the brackets appear in the regex then i get false

console.log(pattern.test("{}()[]") // returns false

I want the string of brackets to match the pattern no matter which brackets comes first or second as long as they meet the above conditions

2

Answers


  1. Let’s write a parser!
    Well since all we care are the parenthesis we can just use a stack data structure as we read from left to right, pushing and popping as we go along.

    var exp1 = "(){(inner)[]}[]"
    var exp2 = "(]"
    
    console.log(checkParenthesis(exp1))
    console.log(checkParenthesis(exp2))
    
    function checkParenthesis(str) {
      var stack = []
      for (const char of str) {
        if (isOpenParenthesis(char)) {
          stack.push(char)
        } else if (isCloseParenthesis(char)) {
          if (stack.length == 0) {
            return false
          }
          if (!compareParenthesis(stack.pop(), char)) {
            return false
          }
        }
      }
      return stack.length == 0
    }
    
    function compareParenthesis(a, b) {
      return a == '(' && b == ')' || a == '[' && b == ']' || a == '{' && b == '}'
    }
    
    function isOpenParenthesis(a) {
      return a == '(' || a == '[' || a == '{'
    }
    
    function isCloseParenthesis(a) {
      return a == ')' || a == ']' || a == '}'
    }
    Login or Signup to reply.
  2. If your task is to match any string that consists of one or more occurrences of a pair of empty brackets/parentheses/braces, you can simply use a regex solution like

    ^(?:()|[]|{})+$
    

    See the regex demo.

    Details

    • ^ – start of string
    • (?:()|[]|{})+ – one or more occurrences of
      • () – a () substring
      • | – or
      • [] – a [] substring
      • | – or
      • {} – a {} substring
    • $ – end of string.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search