0

I'm attempting to convert a C# method to .Net code and I'm having some trouble. Here's the C# line

text = Regex.Replace(text, "{{(.+?)}}", new MatchEvaluator(match => values[match.Groups[1].Value].ToString()));

My first attempt looks like so:

$text = New-Object System.Text.RegularExpressions.MatchEvaluator -ArgumentList @({$values[$args[0].Groups[1].Value].ToString()})

I obviously don't understand how to create delegates in Powershell, and I've been googling for the past hour. Everything I come across seems to fail, so I'm sure I have a fundamental misunderstanding of what's going on. I know MatchEvaluator is itself a delegate type and I think the issue is I don't know how to create delegates from powershell scriptblocks. I keep getting exceptions complaining the method paramenter is null, but I know for a fact that what I'm passing to it isn't null, so I'm lost.

Can anyone help out here?

1 Answer 1

3

You can create delegate by casting to delegate type:

$Delegate=[System.Text.RegularExpressions.MatchEvaluator]{$values[$args[0].Groups[1].Value].ToString()}

But in many cases you can just pass ScriptBlock into method:

$text=[Regex]::Replace($text, "{{(.+?)}}", {$values[$args[0].Groups[1].Value].ToString()})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.