Home > Enterprise >  Returning matching characters from a string array in powershell
Returning matching characters from a string array in powershell

Time:10-21

Im having difficulty with something that is probably simple. Essentially i want to return any instances of a character inside an array, my example here should provide more clarity then this explanation. One thing to note is that ill be doing this in a loop and the index wont be the same nor will the letter in question, therefore as far as im aware i cant .indexof or substring;

$array = "asdfsdgfdshghfdsf"
$array -match "d"

returns: True

What i would like it to return: ddd

Abit like grep in bash

CodePudding user response:

You could use the -replace operator to remove anything that isn't a d:

PS ~> $string = "asdfsdgfdshghfdsf"
PS ~> $string -replace '[^d]'
dddd

Note that all string operators in PowerShell are case-insensitive by default, use -creplace for case-sensitive replacement:

PS ~> $string = "abcdABCD"
PS ~> $string -replace '[^d]'
dD
PS ~> $string -creplace '[^d]'
d

You can generate the negative character class pattern from a string like this:

# define a string with all the characters
$allowedCharacters = 'abc'

# generate a regex pattern of the form `[^<char1><char2><char3>...]`
$pattern = '[^{0}]' -f $allowedCharacters.ToCharArray().ForEach({[regex]::Escape("$_")})

Then use with -replace (or -creplace) like before:

PS ~> 'abcdefgabcdefg' -replace $pattern
abcabc

CodePudding user response:

Using select-string -allmatches, the matches object array would contain all the matches. The -join is converting matches to strings.

$array = 'asdfsdgfdshghfdsf'
-join ($array | select-string d -AllMatches | % matches)

dddd
  • Related