I am trying to parse the digits to store in a variable from a string in VB.NET (would like to also include the decimal point).
Here is an example string: Refund issued for $27.74
I am trying to parse the digits to store in a variable from a string in VB.NET (would like to also include the decimal point).
Here is an example string: Refund issued for $27.74
You don't really need a regex for this, as a simple iteration and comparison of each character from 0-9 (or a call to the static IsNumber method on the Char structure) would do it (sorry for the C# code, it's easy enough to translate into VB.NET):
static IEnumerable<char> GetNumericCharacters(this string s)
{
// Check for null.
if (s == null) throw new ArgumentNullException("s");
// Iterate through the characters.
foreach (char c in s)
{
// If a number, return it.
if (char.IsNumber(c)) yield return c;
}
}
Of course, the regex is just as easy:
[0-9]
You can use the RegEx class to get all the matches for that pattern and concatenate them together.
The only time where each of these solutions fail is when you have multiple numbers in different contexts, e.g.:
"The user purchased 10 items at $0.99 each"
As casperOne already pointed out, one example is not sufficient to give a full solution.
The regular expression string could look like "\\$([0-9]+\\.[0-9]+)"
or "Refund issued for \$(?<Value>[0-9]+\.[0-9]+)"
. The latter being more more restrictive.
The second example also uses a named group. This can make it easier to extract the matches after the call to Regex.Match if you have a more complex scenario.
A nice tool to play around with .net style regular expressions is Expresso.