我需要为此写一个正则表达式patern:
[0:00:07]
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
string pattern = "[[0-9]{1,1}:[0-9]{1,2}:[0-9]{1,2}]";
Run Code Online (Sandbox Code Playgroud)
我有这样的结果:0:00:07].正如你所看到的,我的正则表达式错过了第一个'['.我该如何解决?
如果你需要匹配文字[或]正则表达式,你需要逃避它:
string pattern = @"\[[0-9]:[0-9]{1,2}:[0-9]{1,2}\]";
Run Code Online (Sandbox Code Playgroud)
请参阅RegexStorm演示
注意,这{1,1}等于没有量词(即前面的子模式将匹配一次).
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).