I need to write a regex patern for this:
[0:00:07]
This is my code:
string pattern = "[[0-9]{1,1}:[0-9]{1,2}:[0-9]{1,2}]";
I've got such a result: 0:00:07]
. As you can see, my regex misses the first '['
. How can I resolve it?
If you need to match literal [
or ]
in a regex, you need to escape it:
string pattern = @"\[[0-9]:[0-9]{1,2}:[0-9]{1,2}\]";
See RegexStorm demo
Note, that {1,1}
is equal to no quantifier (i.e. the preceding subpattern will be matched once).
Also, it should be noted that the final ]
does not need escaping as .NET regex engine will treat it as a literal (as it cannot parse it as part of a character class delimiter. HOWEVER, it is a good idea to keep your pattern unambiguous, and escape special characters wherever they appear inside the pattern (it will be very handy if you want to port your regex to another platform).
Escape the first square brace.
\[[[0-9]{1,1}:[0-9]{1,2}:[0-9]{1,2}]
This should work. There are alternate representations as in other answers as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With