Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex pattern for timestamp

Tags:

c#

regex

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?

like image 478
Alexander Avatar asked Dec 19 '22 03:12

Alexander


2 Answers

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).

like image 125
Wiktor Stribiżew Avatar answered Dec 21 '22 17:12

Wiktor Stribiżew


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.

like image 31
Gaurav Mittal Avatar answered Dec 21 '22 17:12

Gaurav Mittal