[英]regular expression for unlimited nested brackets
我正在尋找符合以下情況的正則表達式(在C#中):
等等
{a} {b}
等等
a {b}
到目前為止,我得到的是: 。* [\\ {]。+?[\\}]。*,但這完全匹配大小寫{a} {b} ,而不是返回兩個Matchs,即{a}和{ b}
該表達式用於驗證某些字符串是否為編碼字符串。 如果是這樣,它需要從編碼字符串中獲取單獨的片段(Regex.Matches()會很方便)並進行解析。
您可以通過在正則表達式周圍結合一些遞歸邏輯來做到這一點
此正則表達式將匹配嵌套在三層深的開閉括號,如{a{b{c}}}{{{d}e}f}
\{((?:\{(?:\{.*?\}|.)*?\}|.)*?)\}
虛線區域是基本搜索,其中該搜索嵌套在其內部,可以根據需要放置任意數量的圖層。
在下面的示例中,我只是針對大多數示例運行正則表達式。 將此正則表達式與一個foreach循環結合,該循環將獲取每個組1,並從當前字符串^[^{]*
的開頭捕獲所有未打開的括號,然后通過上方的正則表達式將其余的字符串遞歸反饋以捕獲值在下一組括號內,然后從字符串[^}]*$
的末尾捕獲所有非近括號。
{a}
{a:b}
{a:{b}}
{a:{b:c}}
{a}{b}
{a}{b}{c}
{a{b{c}}}{{{d}e}f}
這個C#.Net示例僅顯示正則表達式的工作方式。 了解第1組如何從最外面的括號組中獲取內部文本。 每個放在方括號中的文本都分為其自己的數組位置,並刪除了相應的在方括號中。
using System;
using System.Text.RegularExpressions;
namespace myapp
{
class Class1
{
static void Main(string[] args)
{
String sourcestring = "sample text above";
Regex re = new Regex(@"\{((?:\{(?:\{.*?\}|.)*?\}|.)*?)\}",RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline);
MatchCollection mc = re.Matches(sourcestring);
int mIdx=0;
foreach (Match m in mc)
{
for (int gIdx = 0; gIdx < m.Groups.Count; gIdx++)
{
Console.WriteLine("[{0}][{1}] = {2}", mIdx, re.GetGroupNames()[gIdx], m.Groups[gIdx].Value);
}
mIdx++;
}
}
}
}
$matches Array:
(
[0] => Array
(
[0] => {a}
[1] => {a:b}
[2] => {a:{b}}
[3] => {a:{b:c}}
[4] => {a}
[5] => {b}
[6] => {a}
[7] => {b}
[8] => {c}
[9] => {a{b{c}}}
[10] => {{{d}e}f}
)
[1] => Array
(
[0] => a
[1] => a:b
[2] => a:{b}
[3] => a:{b:c}
[4] => a
[5] => b
[6] => a
[7] => b
[8] => c
[9] => a{b{c}}
[10] => {{d}e}f
)
)
該表達式僅適用於遞歸的第三級。 外文需要單獨處理。 .net正則表達式引擎確實提供了遞歸計數,並且可能支持N層深度。 如此處所述,此表達式可能無法處理{a:{b}g{h}i}
捕獲g
。
您還可以構建一個例程,該例程僅解析示例字符串中的每個字符並跟蹤嵌套深度。
我提供此Powershell樣本,因為我有一個方便的Powershell控制台。 這僅是為了演示該功能如何工作。
$string = '{a}
{a:b}
a:{b}g{h}ik
{a:{b:c}}
{a}{b}
{a}{b}{c}
{a{b{c}}}{{{d}e}f}
'
$intCount = 0
# split the string on the open and close brackets, the round brackets ensure the squiggly brackets are retained
foreach ($CharacterGroup in $string -split "([{}])") {
write-host $("+" * $intCount)$CharacterGroup
if ($CharacterGroup -match "{") { $intCount += 1 }
if ($CharacterGroup -match "}") { $intCount -= 1 }
if ($intCount -lt 0) {
Write-Host "missing close bracket"
break
} # end if
} # next $CharacterGroup
{
+ a
+ }
{
+ a:b
+ }
a:
{
+ b
+ }
g
{
+ h
+ }
ik
{
+ a:
+ {
++ b:c
++ }
+
+ }
{
+ a
+ }
{
+ b
+ }
{
+ a
+ }
{
+ b
+ }
{
+ c
+ }
{
+ a
+ {
++ b
++ {
+++ c
+++ }
++
++ }
+
+ }
{
+
+ {
++
++ {
+++ d
+++ }
++ e
++ }
+ f
+ }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.