Regex - replace

Welcome Forums General PowerShell Q&A Regex - replace

This topic contains 6 replies, has 3 voices, and was last updated by

 
Participant
2 years, 1 month ago.

  • Author
    Posts
  • #53669

    Participant
    Points: 0
    Rank: Member

    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

    Moderator
    Points: 0
    Team Member
    Rank: Member

    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

    Moderator
    Points: 0
    Team Member
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

    Thanks Daniel! it worked perfectly!

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

  • #54192

    Moderator
    Points: 0
    Team Member
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

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

    Appreciate you remembering and replying!

The topic ‘Regex - replace’ is closed to new replies.