0

I need to extract a number from a string, the number changes all the time so cannot just be hard coded eg:

some random amount of text 54321 more text and another number 123

I know I can use something like:

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

but that gives me 54321123 which is not what I want, I only want the 54321.

Any idea on a regular expression that will do that?

1

2 Answers 2

1

If you know the number of places the number should have (here 5)

$String = "john123456smith"
If ($String -match '^\D*(\d{5}).*$') {
    "Foud number {0}" -f $Matches[1]
} else {
    "no number with 5 places found"
}

Sample output:

Foud number 12345
Sign up to request clarification or add additional context in comments.

Comments

1

Well, based on your description, this should work:

$test = 'asdfasdfasdfadf54321asdfasdfasdf123'
$test -match '[^0-9]+([0-9]+)'
$matches[1]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.