Check If 5th letter in string is number or alphabet

Hello Everyone,

I am able to figure out If this string has numbers or not but not able to find out If 4th character in this string is alphabet or number. If It’s a number then I will have code to run else If it’s alphabet then I have different code to run. Need help with this.

 
<p class=“p1”>$Check = “abc 123”</p>
<p class=“p1”>if($Check -match “[0-9]”)</p>
<p class=“p1”>{</p>
<p class=“p1”> write-host “Number”</p>
<p class=“p1”>}</p>

Code

[String]$Check = 'abc 123'
[String]$FifthCharacter = $Check.ToCharArray()[4]
if ($FifthCharacter -as [Int]) { "The fifth Character '$Character' is a number" } else { 'not' }

Output

The fifth Character '3' is a number

Code

[String]$Check = 'abc 123'
0..($Check.Length -1) | foreach { 
    $Character = [String]$Check.ToCharArray()[$_]
    if ($Character -as [Int]) {
        "The # $($_+1) Character '$Character' is a number"
    } else {
        "The # $($_+1) Character '$Character' is NOT a number"
    }
}

Output

The # 1 Character 'a' is NOT a number
The # 2 Character 'b' is NOT a number
The # 3 Character 'c' is NOT a number
The # 4 Character ' ' is NOT a number
The # 5 Character '1' is a number
The # 6 Character '2' is a number
The # 7 Character '3' is a number

So you’re looking for a string starting with 4 arbitrary charachters followed by a digit? :wink:

“abc 123” -match ‘^.{4}\d’

You may read more about regular expressions online : https://www.regular-expressions.info

Convert the string to a character array and then test the character you need:

$tests = "abc 123","dfded21","dfe234ds"


foreach ($check in $tests) { 
    $arrCheck = $check.ToCharArray()

    if ($arrCheck[4] -match '[0-9]') {
        Write-Host ('Character 5 ({0}) in string "{1}" is a number' -f $arrCheck[4], $Check) -ForegroundColor Green
    }
    else {
        Write-Host ('Character 5 ({0}) in string "{1}" is not a number' -f $arrCheck[4], $Check) -ForegroundColor Red
    }

}

Output:

Character 5 (1) in string "abc 123" is a number
Character 5 (d) in string "dfded21" is not a number
Character 5 (3) in string "dfe234ds" is a number

Thank You Everyone