Dan
Dan

Reputation: 195

Capitalize Specific Words in a String - Powershell

I need to be able to take a sentence in any case and convert it to having the 1st word and each word capitalized except the following words: to, a, the, at, in, of, with, and, but, or

example: "hello how are you dan" needed result: Hello How are You Dan"

Now I know this looks like homework but I am at the point that I need to learn by seeing correct script usage. Lots of effort has been put in to figure out how to do this but I need someone to bridge the gap by showing me the correct method...then I can review it and learn from it.

Upvotes: 1

Views: 2334

Answers (3)

Kiran Reddy
Kiran Reddy

Reputation: 2904

 $string = 'hello how are you dan to, a, the, at, in, of, with, and, but, or'
[Regex]::Replace($string, '\b(?!(are|to|a|the|at|in|of|with|and|but|or)\b)\w', { param($letter) $letter.Value.ToUpper() })

Regex Explanation:

\b #Start at the beginning of a word.

(?!(are|to|a|the|at|in|of|with|and|but|or)   #match only if a word does not begin with "to, a, the, at, in, of, with, and, but, or"

\b #Second \b to signify that there are no characters after the words listed in the negative lookahead list.

\w  #Match any single word character

$letter.Value.ToUpper()  # convert the matched letter(value) to uppercase

Negative Lookahead

Regex101 Link

Upvotes: 3

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

Windos' answer is spot on, but I'm bored, so here is a fully working implementation:

function Get-CustomTitleCase {
    param(
        [string]$InputString
    )

    $NoCapitalization = @(
        'are',
        'to',
        'a',
        'the',
        'at',
        'in',
        'of',
        'with',
        'and',
        'but',
        'or')

    ( $InputString -split " " |ForEach-Object {
        if($_ -notin $NoCapitalization){
            "$([char]::ToUpper($_[0]))$($_.Substring(1))"
        } else { $_ }
    }) -join " "
}

Use it like this:

PS C:\> Get-CustomTitleCase "hello, how are you dan"
Hello, How are You Dan

Upvotes: 4

Windos
Windos

Reputation: 1946

I won't give you a complete script, but I can pseudo code this to hopefully put you on the right track.

First of all, create an array of strings containing all the words you don't want to capitalize.

The split the input string ('hello how are you dan') by spaces. You should end up with an array similar to 'hello', 'how', 'are'...

Loop through the split up string, and see if the word is in the first array you created.

If it is, ignore it, but if it isn't you want to take the first letter and use a string method to ensure it is in it's uppercase form.

You then need to join the string back up (don't forget the spaces.) You could either reconstruct the string ready for output as you're looping through the split array or at the end.

(Emphasis added to hint towards certain keywords you'll be after.)

Upvotes: 2

Related Questions