The [regex] thing...

This topic contains 3 replies, has 2 voices, and was last updated by Profile photo of Don Jones Don Jones 2 years, 1 month ago.

  • Author
    Posts
  • #24532
    Profile photo of JC
    JC
    Participant

    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?

  • #24539
    Profile photo of Don Jones
    Don Jones
    Keymaster

    Well... that isn't really "PowerShell" code, it's .NET code.

    This:

    match($text,'?).+(?=\)',"singleline")

    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:

    .value.trim()

    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.

  • #24543
    Profile photo of JC
    JC
    Participant

    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.

  • #24546
    Profile photo of Don Jones
    Don Jones
    Keymaster

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

You must be logged in to reply to this topic.