c# – 正则表达式只能得到包含数字的方括号,但不在方括号内
发布时间:2020-12-15 08:48:19 所属栏目:百科 来源:网络整理
导读:示例字符串 "[] [ds*[000112]] [1448472995] sample string [1448472995] ***"; 正则表达式应该匹配 [1448472995] [1448472995] 因为有外方括号,所以不应该匹配[000112]. 目前我的这个正则表达式也匹配[000112] const string unixTimeStampPattern = @"[([0
示例字符串
"[] [ds*[000112]] [1448472995] sample string [1448472995] ***"; 正则表达式应该匹配 [1448472995] [1448472995] 因为有外方括号,所以不应该匹配[000112]. 目前我的这个正则表达式也匹配[000112] const string unixTimeStampPattern = @"[([0-9]+)]"; 解决方法
这是使用平衡文本执行此操作的好方法.
( [ d+ ] ) # (1) | # or,[ # Opening bracket (?> # Then either match (possessively): [^[]]+ # non - brackets | # or [ # [ increase the bracket counter (?<Depth> ) | # or ] # ] decrease the bracket counter (?<-Depth> ) )* # Repeat as needed. (?(Depth) # Assert that the bracket counter is at zero (?!) ) ] # Closing bracket C#样本 string sTestSample = "[] [ds*[000112]] [1448472995] sample string [1448472995] ***"; Regex RxBracket = new Regex(@"([d+])|[(?>[^[]]+|[(?<Depth>)|](?<-Depth>))*(?(Depth)(?!))]"); Match bracketMatch = RxBracket.Match(sTestSample); while (bracketMatch.Success) { if (bracketMatch.Groups[1].Success) Console.WriteLine("{0}",bracketMatch); bracketMatch = bracketMatch.NextMatch(); } 产量 [1448472995] [1448472995] (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |