1

Why does the empty item not match '\s*'? There are zero or more whitespace characters in the second item.

PS C:\> @('now','','is') | ?{ $_ -ne '' }
now
is
PS C:\> @('now','','is') | ?{ $_ -ne '\s*' }
now

is
lit
  • 14,456
  • 10
  • 65
  • 119

1 Answers1

2

You would have to use the -match operator instead of the inequality operator you're currently using:

PS> @('now','','is') | ?{ $_ -match '\s*' }
now

is

However, since you're matching the empty string as well (and it may appear at any position in the input string), everything matches this regex. So perhaps you'd want to just match strings that are either empty or completely whitespace by anchoring the pattern:

PS> @('now','','is') | ?{ $_ -match '^\s*$' }

# ^ there is an empty line, it's just a bit invisible
Joey
  • 344,408
  • 85
  • 689
  • 683
  • Many thanks, @Joey. I thought I had tried this. – lit Jun 21 '21 at 16:42
  • My bad on `''` being `$null` but what is `where-object` considering `''` to be? Since `@('now','','is') | ?{ $_ }` would already be filtering the empty string. I'm wondering what is happening under the hood. – Santiago Squarzon Jun 21 '21 at 16:55
  • 1
    Nicely done, though note that you've inverted the original logic. @SantiagoSquarzon, whatever `Where-Object` outputs is coerced to a Boolean, and `''` is implicitly `$false`, whereas any non-empty string (irrespective of its content) is implicitly `$true` - see the bottom section of [this answer](https://stackoverflow.com/a/53108138/45375) for a summary of PowerShell's to-Boolean coercion logic. – mklement0 Jun 21 '21 at 18:42