Determine the index of a numerical character

Asked

Viewed 28 times

1

How can I store the position of the first numeric character of a string?

Example:

$NomeEstacao = "Atendimento05" # posição 11 (carácter 0)
$NomeEstacao = "Direcao46" # posição 7 (carácter 4)

I tried to use $a.IndexOf("\d"). to find the position but without success.

1 answer

0


You can do the following:

$NomeEstacao = "Atendimento05" 
if ($NomeEstacao  -match "(?<digito>\d)") {
    $pos = $NomeEstacao.IndexOf($Matches.digito)
    Write-Host $pos
}

The -match looks for the first digit in string and then the .IndexOf(...) returns the position of the digit. You also have the bonus if you want to know which was the first digit found.

  • I know the site does not recommend comments of thanks. But thanks for the tip. It will be very useful.

  • No problem, usually the expected is recommended and vote on the answer if it helped you and, as in your case, if the question is yours, mark the answer as a solution. That said there is no problem in thanking.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.