programing

Powershell의 람다 식

elecom 2023. 8. 6. 09:50
반응형

Powershell의 람다 식

나는 C#에 람다 식을 사용하여 메소드로 전달하는 코드를 가지고 있습니다.PowerShell에서 이를 달성하려면 어떻게 해야 합니까?예를 들어 다음은 C# 코드입니다.

string input = "(,)(;)(:)(!)";
string pattern = @"\((?<val>[\,\!\;\:])\)";
var r = new Regex(pattern);
string result = r.Replace(input, m =>
    {
        if (m.Groups["val"].Value == ";") return "[1]";
        else return "[0]";
    });
Console.WriteLine(result);

다음은 람다 식이 없는 PowerShell 스크립트입니다.

$input = "(,)(;)(:)(!)";
$pattern = "\((?<val>[\,\!\;\:])\)";
$r = New-Object System.Text.RegularExpressions.Regex $pattern
$result = $r.Replace($input, "WHAT HERE?")
Write-Host $result

참고: 제 질문은 이 정규 표현 문제를 해결하는 것이 아닙니다.PowerShell에서 대리인을 받는 메서드에 람다 식을 전달하는 방법을 알고 싶습니다.

PowerShell 2.0에서는 스크립트 블록을 사용할 수 있습니다.{ some code here }) 대리인:

$MatchEvaluator = 
{  
  param($m) 

  if ($m.Groups["val"].Value -eq ";") 
  { 
    #... 
  }
}

$result = $r.Replace($input, $MatchEvaluator)

또는 메소드 호출에서 직접:

$result = $r.Replace($input, { param ($m) bla })

팁:

사용할 수 있습니다.[regex]문자열을 정규식으로 변환하는 방법

$r = [regex]"\((?<val>[\,\!\;\:])\)"
$r.Matches(...)

가끔은 이런 것을 원할 때도 있습니다.

{$args[0]*2}.invoke(21)

(익명의 '함수'를 선언하고 즉시 호출합니다.)

이 오버로드를 사용할 수 있습니다.

[regex]::replace(
   string input,
   string pattern, 
   System.Text.RegularExpressions.MatchEvaluator evaluator
)

딜러는 스크립트 블록(람다 표현식)으로 전달되며 $args 변수를 통해 MatchEvaluator에 액세스할 수 있습니다.

[regex]::replace('hello world','hello', { $args[0].Value.ToUpper() })

언급URL : https://stackoverflow.com/questions/10995667/lambda-expression-in-powershell

반응형