不遵守非贪婪的指标吗

不遵守非贪婪的指标吗

下面的代码返回:

partner=<Partner>
 more stuff <Name>Test</Name>
 other things </Partner>  <Partner>
 more stuff <Name>CompanyX</Name>
 other things </Partner>

但我希望它返回:
partner=<Partner>
 more stuff <Name>CompanyX</Name>
 other things </Partner>

样例代码:
$partyName = "CompanyX"

#$bindings = [IO.File]::ReadAllText($inputFileName)

$bindings = "starting stuff <Partner>`r`n more stuff <Name>Test</Name>`n other things </Partner>  <Partner>`r`n more stuff <Name>CompanyX</Name>`n other things </Partner> ending stuff"


$found = $bindings -match "(?s)(<Partner>.*?<Name>$partyName</Name>.*?</Partner>)"

if ($found)
{
    Write-Host "matched"
    $partner = $matches[1]
}

Write-Host "partner=$partner "

最佳答案

正如TheIncorrigible1所说:使用xml解析器代替正则表达式。

但是,由于使用正则表达式执行此操作的原因可能只是参见IF和HOW,可以使用正则表达式来完成,因此可以使用:

$found = $bindings -match "(?sx)(<Partner>(?:((?!</Partner>).)+<Name>$([Regex]::Escape($partyName))</Name>)(?:((?!</Partner>).))*</Partner>)"

关于regex - Powershell RegEx-捕获 “too much”(不遵守非贪婪的指标吗?),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51793850/

10-12 02:02