gpt4 book ai didi

c# - 正则表达式获取仅包含数字但不在方括号内的方括号

转载 作者:太空狗 更新时间:2023-10-29 21:32:46 26 4
gpt4 key购买 nike

示例字符串

 "[] [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]

关于c# - 正则表达式获取仅包含数字但不在方括号内的方括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35610047/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com