如何提取方括号之间的字符串

adz*_*adz -1 regex powershell groovy

我必须使用 Powershell 或 Groovy 脚本从方括号中提取字符串。

电源外壳 :

$string = "[test][OB-110] this is some text"  

$found = $string -match '(?<=\[)[^]]+(?=\])'  
echo $matches
Run Code Online (Sandbox Code Playgroud)

当我运行上面的代码时,它返回:

test 
Run Code Online (Sandbox Code Playgroud)

我希望它返回这个:

test
OB-110
Run Code Online (Sandbox Code Playgroud)

我需要提取括号内的所有文本。

Mat*_*sen 5

-matchRegex.Match()在后台内部调用,而后者只会捕获第一个匹配项。

Select-String-AllMatches开关一起使用:

($string |Select-String '(?<=\[)[^]]+(?=\])' -AllMatches).Matches.Value
Run Code Online (Sandbox Code Playgroud)

或者Regex.Matches()直接调用:

[regex]::Matches($string, '(?<=\[)[^]]+(?=\])').Value
Run Code Online (Sandbox Code Playgroud)