Simple Remove things between Parenthesis- REGEX

This topic contains 0 replies, has 1 voice, and was last updated by  Forums Archives 5 years, 9 months ago.

  • Author
    Posts
  • #5057

    by suave9987 at 2012-08-29 09:33:57

    Hello ALL!

    I have a simple task but I cannot seem to get it down. I have lines that look like this:

    A000000018210C0300000000000002(?....!.........)
    A00000001820020203000000424950(?..........BIP)
    A000000521F00010(?...!?..)
    A000000521F00002(?...!?..)

    And all I want to do is remove the paranthesis and everything in between them so to just leave this:

    A000000018210C0300000000000002
    A00000001820020203000000424950
    A000000521F00010
    A000000521F00002

    I know that in python the REGEX expression may be this:

    re.sub(r'\([^)]*\)', ", filename)

    and I am identifying the REGEX expression to be this:

    ' \([^)]*\)'

    And so I tried to construct the powershell script this way:

    Function StripGSF2{
    $file1 = "file.txt"
    (Get-Content $file1)|Foreach-Object {
    $_ -replace '' \([^)]*\)'', ''`
    }| Set-Content $file1
    }

    But this does not work.

    I may be missing the boat on this one as well so forgive me for the bad script.

    Thanks!

    by suave9987 at 2012-08-29 09:50:58

    Actually I kept playing around more with this and found what I think the solution may be. This works for me:

    Function StripGSF2{
    $file1 = "file.txt"
    (Get-Content $file1)|Foreach-Object {
    $_ -replace '\(([^\)]+)\)', ''
    }| Set-Content $file1
    }

    Let me know if anyone agrees and thanks for viewing!

    by poshoholic at 2012-08-29 11:12:18

    Sure, that works. You can simplify it a little if you like, to this:

    $_ -replace '\([^\)]+\)'

    All I changed in the regex was to remove the capturing brackets since you don't need to capture anything. Also, by leaving off the empty string PowerShell knows you're simply removing any matches (replacing them with nothing). Your solution is just fine as is though.

    by suave9987 at 2012-08-29 11:56:44

    Great! Ok thank you.

    I am always looking to simplify my code and it is great to have feedback from a MVP.

    Thanks again!

You must be logged in to reply to this topic.