Search code examples
regexpreg-replacepreg-matchregular-language

Regex to find string where parenthesis are not closed


I need a regex to find strings where parenthesis are not closed

Example:

02 Back for Good (Radio Mix.mp3

Find "(Radio Mix"

But if

02 Back for Good (Radio Mix).mp3

Must find nothing


Solution

  • If you want to capture up until the file extension, you can do this:

    \([^\)]*(?=\.\w+$)
    

    https://regex101.com/r/cB1jG2/1

    It looks for an opening bracket followed by anything except a closing bracket, and then a positive lookahead to find a file extension at the end of the string.

    If you know the possible file extensions, you can be more literal:

    \([^\)]*(?=\.(?:wav|mp3)$)
    

    And if you can have nested parentheses, this can match some cases, but not all and can probably be reduced to something cleaner:

    \((?:\([^\(\)]*?\)|[^\)])*(?=\.\w+$)
    

    https://regex101.com/r/aQ1eO3/1