The [regex] thing...

I’m just looking thrugh a script that contains following line

$x = [regex]::match($text,’?).+(?=)’,“singleline”).value.trim()

Would someone mind explaining what’s going on here?
I’m guessing the expression is looking thrugh the contents of text contained in variable $text to fined a match for the word “domain” but if it was that simple it would only be $text -match “domain” so what’s all the rest doing then?

Well… that isn’t really “PowerShell” code, it’s .NET code.



is basically the same as using -match. The static Match() method isn’t precisely the same syntax as -match, but you can accomplish the same stuff.

The rest:


Is taking the result of the match and removing leading and trailing whitespace. You could obviously do that in PowerShell using a couple of different forms of syntax.

This isn’t so much a question of one approach being better than another; it’s likely the person who wrote that was just more comfortable with that syntax, and PowerShell lets you use it. Almost anything in PowerShell can be done in ten different ways.

Thanks Don. .NET eh. Now I know I can safely convert this to something I’m more familar with. When looking up regular expressions in Powershell I often seen references to Perl. I suppoese it’s yet another method of doing things in Powershell.

Well, yes and no. Perl has a specific regex syntax; .NET doesn’t use exactly that. There are other variants of the syntax, too.