Regex - replace

This topic contains 6 replies, has 3 voices, and was last updated by  Recco Bucceri 1 year, 10 months ago.

  • Author
  • #53669

    Recco Bucceri

    Hey all,

    I am still finding my way with Regex, but i have hit a bit of a brick wall and need some help pushing through.

    I have a PST uploader for office 365 and when a user uploads a pst file it is saved on the server as jon.doe@constoso.com_1.pst. Now through powershell i am attempting to remove the _1.pst (keep in mind the domain name might change and the number can increment up as more uploads from the same user are received).

    So I have the following:

    $Displayname = "jon.doe@constoso.com_1.pst"

    $DisplayName -replace "(_[0-9]).pst$"

    When i use the following, the _ and number are removed, but not the .pst isnt.

    I think i am close, just missing something simple...

  • #53677

    Daniel Krebs

    I would remove the brackets () and escape the dot with a backslash. You don't really need the brackets to create a group in this case.

    $DisplayName -replace "_[0-9]\.pst$"

  • #53679

    Daniel Krebs

    And replace the double quotes with singles or escape the dollar-sign with a backtick.

    $DisplayName -replace '_[0-9]\.pst$'

    $DisplayName -replace "_[0-9]\.pst`$"

  • #53719

    Craig Duff

    I agree with the improvements that Daniel mentioned. However, your regex does remove the .pst for me and it should for you. Can you post the regex in context of the surrounding code?

  • #53910

    Recco Bucceri

    Thanks Daniel! it worked perfectly!

    Out of curiosity, when do you use the () in regex?

  • #54192

    Daniel Krebs

    Apologies for my delayed reply. I've been on the move quite a bit since September 6th without access to a PC.

    () are used in regular expressions to define a capturing group to extract data. You can read more about capturing groups here:

    PowerShell Example:

  • #54194

    Recco Bucceri

    Awesome thanks for this. Ill check the links as well.

    Appreciate you remembering and replying!

You must be logged in to reply to this topic.