PowerShell - Replacing all occurrences, except one, of a certain character in a string

Writing a PS form in SAPIEN PS studio 2018.

Problem: I have a random string, in text box, that contains square brackets in it ('[' or ']')

Expected: Need to allow the user to type only one brackets sequence

For example:

1> bla[]bla //valid 2> []bla //valid 3> bla[[] // not valid 4> b[la[] // not valid 5> b]la[] // not valid etc.. 

My code so far(Used the solution from here):

if ($this.Text -match '(\[){2,}') { $this.Text = $this.Text -replace '(.*?)\[(.*)', '$1$2' } if ($this.Text -match '(\]){2,}') { $this.Text = $this.Text -replace '(.*?)\](.*)', '$1$2' } 

This code works only when the brackets are matched together(example 3), but it doesn't work for example 4 and 5, any suggestions please?

ANSWER, by Lieven Keersmaekers

@('bla[]bla','[]bla','bla[[]','b[la[]','b]la[]') | % { $_ -replace '\[.*\]', '[]' -replace '\](?=.*\[)'} 
8

1 Answer

Following works for the examples and constraints you've given

-replace '\[.*\]', '[]' -replace '\](?=.*\[)' 

The gist of this is to

  • '\[.*\]', '[]' removes everything between the first open and last closing bracket
  • '\](?=.*\[)'removes remaining closing brackets having a positive lookahead for an opening bracket

Example

@('bla[]bla','[]bla','bla[[]','b[la[]','b]la[]') | % { $_ -replace '\[.*\]', '[]' -replace '\](?=.*\[)'} 

Returns

bla[]bla []bla bla[] b[] bla[] 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like