- $str = '[abc]d[ef]g123';
- $reg = '(?<=\[[^[\]]*\]|^)[^[\]]+';
- [regex]::Replace($str, $reg, {param($m), $m.Groups[0].Value.ToUpper()});
复制代码 结果:[abc]D[ef]G123
如果需要考虑括弧嵌套的问题:- $str = '[abc[w8w]]de[fg]xy123';
- $reg = '\[(?:[^[\]]*|\[(?<open>)|\](?<-open>))*(?(open)(?!))\]|[^[\]]+';
- [regex]::Replace($str, $reg, {param($m), $s = $m.Groups[0].Value; if($s.IndexOf('[')+1){$s}else{$s.ToUpper()}});
复制代码 结果:[abc[w8w]]DE[fg]XY123 |