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

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 '\](?=.*\[)'}
  • Why not just check for the existence of an opening bracket and if that is the case for [<whatever>]? Your example text doesn't make a lot of sense so it's hard to tell whenever there might not be a better example. – Seth Sep 11 at 7:54
  • You mean by stack? – igor Sep 11 at 7:56
  • Essentially you're interested in whenever you have proper bracket (nesting). As you only want to allow a single bracket pair (as I understand it) just use strpos([) > strpos(]) and as all you do is just remove the bracket just use a simple replace to replace those brackets with nothing. – Seth Sep 11 at 8:17
  • How do you know which bracket to remove in your fourth example? – Lieven Keersmaekers Sep 11 at 8:38
  • 1
    This works for the examples you've given @('bla[]bla','[]bla','bla[[]','b[la[]','b]la[]') | % { $_ -replace '\[.*\]', '[]' -replace '\](?=.*\[)'} – Lieven Keersmaekers Sep 11 at 10:05

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


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



Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.