本帖最后由 WHY 于 2023-3-13 23:40 编辑
- Function Get-BalanceSet([ref]$str){
- $index = $str.Value.IndexOf('abc(');
-
- if ($index -lt 0){ #不含 'abc(' 子串,退出函数
- return;
- }
-
- $str.Value = $str.Value.SubString($index); #删掉 'abc(' 之前的所有字符
- $arr = [Collections.ArrayList]@();
-
- $n = 0;
- $m = 0;
-
- for ($i=0; $i -lt $str.Value.Length; $i++){ #遍历字符串每个字符
- $s1 = $str.Value.SubString($i, 1); #截取第i个字符,赋值给$s1
- [void]$arr.Add($s1); #再将$s1存放到数组
- if ( $s1 -eq ')' ){ #右括弧,n减1
- $n--;
- } elseIf ( $s1 -eq '(' ){ #左括弧,n加1
- $n++;
- $m++;
- }
- if ($n -eq 0 -and $m -gt 0){ #若n=0且左括弧数不为0
- [void]$out.Add($arr -join ''); #匹配结果存放到$out
- break; #退出For
- }
- }
- $str.Value = $str.Value.SubString(4); #删除开头的 'abc(' 4个字符
- Get-BalanceSet ([ref]$str.Value); #递归
- }
-
- $s = 'xzc abc(s "(abc)"); dfg(); abc(123(ggg))';
-
- $out = [Collections.ArrayList]@(); #数组,存放结果
- Get-BalanceSet ([ref]$s);
- $out;
-
- echo 'Done';
- [Console]::ReadLine();
复制代码
|