Ralf_Reddings
Ralf_Reddings

Reputation: 1569

Select-String RegEx how to select only '}' in this example

Lets say I have string like so:

foo
}
bar}
    }
{baz}

and I only want to match closing braces that are at the start of a line or are preceded by a white space such as one or more tab characters.

So with the above sample, only the braces at line 2 and 4 should be selected (counting from 1)

This first attempt seems to only highlight, the closing brace at line 2, the brace at line 4 is not selected:

"foo
}
bar}
    }
{baz}" |Select-String "\n\s?\}" -AllMatches

I tried making the whitespace token optional with ?, but then the brace at line 2 is deselected:

"foo
}
bar}
    }
{baz}" |Select-String "\n\s+?\}" -AllMatches

hmm...I am pretty sure I would have succeeded with -replace or -match by now but I really need to get the hang of Select-String.

Upvotes: 1

Views: 56

Answers (1)

mklement0
mklement0

Reputation: 440412

"foo
}
bar}
    }
{baz}" | Select-String '(?m)^[ \t]*\}' -AllMatches
  • Use inline option (?m) to make ^ (and $) match the start (and end) of each line.

  • Use [ \t]* to match any run of zero or more (*) spaces or tabs ([ \t])

    • Note: \s*, for matching all whitespace chars., would potentially match across lines, given that newlines are whitespace too.

Upvotes: 2

Related Questions