To match a substring between the first [
and last ]
, you may use
\[.*\] # Including open/close brackets
\[(.*)\] # Excluding open/close brackets (using a capturing group)
(?<=\[).*(?=\]) # Excluding open/close brackets (using lookarounds)
See a regex demo and a regex demo #2.
Use the following expressions to match strings between the closest square brackets:
Including the brackets:
\[[^][]*]
- PCRE, Python re
/regex
, .NET, Golang, POSIX (grep, sed, bash)
\[[^\][]*]
- ECMAScript (JavaScript, C++ std::regex
, VBA RegExp
)
\[[^\]\[]*]
- Java regex
\[[^\]\[]*\]
- Onigmo (Ruby, requires escaping of brackets everywhere)
Excluding the brackets:
(?<=\[)[^][]*(?=])
- PCRE, Python re
/regex
, .NET (C#, etc.), ICU (R stringr
), JGSoft Software
\[([^][]*)]
- Bash, Golang - capture the contents between the square brackets with a pair of unescaped parentheses, also see below
\[([^\][]*)]
- JavaScript, C++ std::regex
, VBA RegExp
(?<=\[)[^\]\[]*(?=])
- Java regex
(?<=\[)[^\]\[]*(?=\])
- Onigmo (Ruby, requires escaping of brackets everywhere)
NOTE: *
matches 0 or more characters, use +
to match 1 or more to avoid empty string matches in the resulting list/array.
Whenever both lookaround support is available, the above solutions rely on them to exclude the leading/trailing open/close bracket. Otherwise, rely on capturing groups (links to most common solutions in some languages have been provided).
If you need to match nested parentheses, you may see the solutions in the Regular expression to match balanced parentheses thread and replace the round brackets with the square ones to get the necessary functionality. You should use capturing groups to access the contents with open/close bracket excluded: