यह संतुलित पाठ का उपयोग कर यह करने के लिए एक अच्छा तरीका है।
(\[ \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
सी # नमूना
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]
दूसरे शब्दों में, आप केवल एक ब्रैकेट किए गए नंबर से मेल खाना चाहते हैं यदि समान संख्या (संतुलित) खोलने और बंद करने वाले ब्रैकेट का पालन करें? –
नेस्टेड ब्रैकेट को बाहर करने के लिए आपको संतुलित टेक्स्ट रेगेक्स का उपयोग करना होगा। – sln
@ टिम: हाँ आप सही हैं। – Sameer