正则表达式只能得到包含数字的方括号,但不在方括号内

Sam*_*eer 6 .net c# regex

示例字符串

 "[] [ds*[000112]] [1448472995] sample string [1448472995] ***";
Run Code Online (Sandbox Code Playgroud)

正则表达式应该匹配

 [1448472995] [1448472995]
Run Code Online (Sandbox Code Playgroud)

[000112]因为有外方括号,所以不应该匹配.

目前,我有这个正则表达式是匹配[000112] 以及

const string unixTimeStampPattern = @"\[([0-9]+)]";
Run Code Online (Sandbox Code Playgroud)

小智 4

这是使用平衡文本来做到这一点的好方法。

    ( \[ \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
Run Code Online (Sandbox Code Playgroud)

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();
}
Run Code Online (Sandbox Code Playgroud)

输出

[1448472995]
[1448472995]
Run Code Online (Sandbox Code Playgroud)