1

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

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.