Regex - replace

This topic contains 6 replies, has 3 voices, and was last updated by Profile photo of Recco Bucceri Recco Bucceri 2 months, 3 weeks ago.

  • Author
    Posts
  • #53669
    Profile photo of Recco Bucceri
    Recco Bucceri
    Participant

    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
    Profile photo of Daniel Krebs
    Daniel Krebs
    Participant

    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
    Profile photo of Daniel Krebs
    Daniel Krebs
    Participant

    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
    Profile photo of Craig Duff
    Craig Duff
    Participant

    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
    Profile photo of Recco Bucceri
    Recco Bucceri
    Participant

    Thanks Daniel! it worked perfectly!

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

  • #54192
    Profile photo of Daniel Krebs
    Daniel Krebs
    Participant

    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: http://www.regular-expressions.info/refcapture.html

    PowerShell Example:

  • #54194
    Profile photo of Recco Bucceri
    Recco Bucceri
    Participant

    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.