3

Given a string with a numeric value in it, I need to extract that value and assign it to a variable. I use the following to accomplish that:

Dim m as Match = Regex.Match(str, "\d+")
If m.Success Then
    test = m.Groups(0).Value
End If

It works fine for string like this one:

This is a 4308 number

I get 4308 extracted. However, if the numeric value contains commas or dots:

This is a 4,308 number

Then, the value extracted is 4 instead of 4,308 or 4308.

How can I modify my regular expression to retrieve the whole number whether or not it contains commas and/or dots?

1 Answer 1

5

You can add the comma and perhaps a dot to the character class:

Dim m as Match = Regex.Match(str, "[\d.,]+")

This one is too crude since it allows strings like .,567,...

You should use

Dim m as Match = Regex.Match(str, "\d+(?:[.,]\d+)*")

It will match numbers like 1, 1,235, 2,456.56, 1,254,456.45, etc.

See RegexStorm demo

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

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.