Powershell Get number from string

Slightly different than OP's question, but I landed here seeking my answer, so...

If there is a "second" set of digits in the string, none of these work correctly to extract the FIRST number in the string.

For instance, using the other answers on the string "asld_1234_asdf3" produces things like "12343" (extra "3" appended to the number).

My real use case has a delimiter - the "_" - as in the example:

    $str = "asld_1234_asdf3";
    $str -replace '.*_([0-9]*)_.*','$1'
    # produces: 1234

If delimiters aren't in play, you need this one (which also works for the case above WITH delimiters, incidentally):

    $str = "asldX1234Yasdf3";
    $str -replace '\D+([0-9]*).*','$1' 
    # produces: 1234

Both of the above produce "1234" as required for my case.


This is simple to do with a regex:

 ('jsmit123456') -replace '\D+(\d+)','$1'

 123456

\D+ = all the non-digits, \d+ = all the digits that follow.

 $studentid = $object.SAMAccountName -replace '\D+(\d+)','$1'

You should use a regex which is some more generic. For example, to cover non-digit characters before AND after the value. Ex: ??XXXX12345YYYY**

You should use:

('??XXXX12345YYYY**') -replace '\D+(\d+)\D+','$1'

$studentid = $object.SAMAccountName -replace '\D+(\d+)\D+','$1'

12345


For readability reasons (which I sometimes find difficult with regexp) I would prefer this solution:

'john123456smith' -replace "[^0-9]" , ''

123456

Replace everything which is not a number, [^0-9], with nothing, ''. This does not involve the $1 syntax (the string matched by the regex)