Put both the opening and closing square brackets in the negated character class?
\\[([^][]+)\\]
\\[
matches a literal [
\\]
matches a literal ]
[^][]
is a negated class, which for instance matches any character except ][
. It might be a little difficult to see it, but it's equivalent to [^\\]\\[]
. Here the double escapes are not required because you are using a character class (just like \\.
is equivalent to [.]
)
([^][]+)
captures everything within square brackets, making sure there's no ]
or [
inside.
In C#, you can use the @
symbol to avoid having to double escape everytime and using this makes the regex like that:
var regex = new Regex(@"\[([^][]+)\]");
Note: This regex will capture everything within square brackets. If you wish to specificly get the format ["how to tie a tie",0]
, you can be more precise. After all, the regex will only match stuff you make it match:
var regex = new Regex(@"\["[^"]+",0\]");
Here, we have another negated character class: [^"]
. This will match any character which is not a quote character.
This one assumes that the digit is always 0
, as depicted in your sample text block. If you have multiple possibilities of numbers, you can use the character class [0-9]+
:
var regex = new Regex(@"\["[^"]+",[0-9]+\]");
You can use \d+
as well, but this character class also matches other characters which may or may not render the regex worse. If you want to be more even cautious by allowing possible spaces, tabs, newlines, form feeds in between the characters, you can use this regex:
var regex = new Regex(@"\[\s*"[^"]+"\s*,\s*[0-9]+\s*\]");
Conclusion, there might be many regexes which suit what you need, just make sure you know how your data is coming through so you can pick one which has the right amount of freeway.