javascriptregexmatch

Regex to match string with contains closed brackets


I need to create regex rule to match string with doesnt' contain ( ) character and also strings that have them inside but always closed (but not nested. Another thing that empty () is also wrong

Good strings (should be matched):

aaaaaa
(asdasd)
aaaa(bbb)a
(aaa)aaaa
aaaaaa(aaaa)
aaaa(bbb)(ccc)ddd
aaaa(bbbb)cccc(dddd)eeee

Bad strings (there shouldn't be match):

)aaaa
)aaaa(asd)
aaaaaa(
aaaa(bbb))
aaa(bbb
aaaaa((bbbb)cccc
aaaa(bbbb))ccc
aaaa(aasd(adssad))ad
adassd(aas(add)adsa(asda)ad)
()

Tried and created something like this (?!.*[(]{2,})(?!.*[)]{2,})(?![)])(?!.*[(]$).*$ but still it isn't good. Any help with this?


Solution

  • You can use this regex for your job:

    /^(?!$)(?:[^)(]*\([^()]+\))*[^)(]*$/gm
    

    RegEx Demo

    RegEx Breakup: