示例字符串
"[] [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]