Visit the acronym exercise on Exercism to read the full instructions and download the exercise files.
Dig Deeper
Regular expression
Using regex
Function Get-Acronym() {
[CmdletBinding()]
Param (
[string]$Phrase
)
(-join ([regex]::Matches($Phrase, "\p{L}+'?\p{L}*") | ForEach-Object { $_.Value[0] })).ToUpper()
}
This approach use the regex class from .NET to match potential words inside the phrase using a specific pattern.
[regex]::Matches($Phrase, "\p{L}+'?\p{L}*")
The pattern match any regular word and those that have apostrophe inside it, for example doesn't or Halley's in a test case.
We then collect the matched objects and loop over them, extracting the match value first index, which is the first char of each word.
ForEach-Object { $_.Value[0] }
Then we call the -join operator upon the collection to turn this into a string, and then call the string method .ToUpper() to make sure it is all in uppercase to fit with acronym behavior.
Regex expression for .NET
String methods
Using string methods
Function Get-Acronym() {
[CmdletBinding()]
Param (
[string]$Phrase
)
( $Phrase -replace "[-_]"," " -split " " | Foreach-Object {$_[0].ToString().ToUpper()} ) -join ""
}
Find and replace strings.
About Split operator.
About Join operator.
Loop and boolean
Using foreach loop and boolean values
Function Get-Acronym() {
[CmdletBinding()]
Param (
[string]$Phrase
)
$newWord = $true
foreach ($char in $Phrase.ToCharArray()) {
if ($newWord -and $char -match "[a-z]") {
$acronym += $char
$newWord = $false
}
if (-not $newWord -and $char -match "[_\- ]") {
$newWord = $true
}
}
$acronym.ToUpper()
}
This approach use a flag with a boolean value to mark when a new word is about to begin or not.
$newWord = $true
We then loop over the characters from the input using foreach and .ToCharArray() method.
If we are about to start a new word (true) and the current char is a letter, then we add that letter to the result, and switch the flag to false.
If we are not in phase of starting a new word (false) and the current char match one of the delimiters, then we switch the flag to true, signify that we are ready to start a new word.
foreach ($char in $Phrase.ToCharArray()) {
if ($newWord -and $char -match "[a-z]") {
$acronym += $char
$newWord = $false
}
if (-not $newWord -and $char -match "[_\- ]") {
$newWord = $true
}
}
$acronym.ToUpper()
After the loop is finished, we call ToUpper() method on the result and got our acronym in all capitalized letters.
Booleans.
Foreach loop.
Source: Exercism powershell/acronym