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
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.
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.