jason jason - 3 months ago 28
C# Question

Extract double from any location inside string in C#

I'm trying to extract double from a string like this :

Regex regex = new Regex(@"^-?\d+(?:\.\d+)?");
Match match = regex.Match(mystring);
if (match.Success)
double number = double.Parse(match.Value);

And my string is like this : "STR/STR: 1.25"

However Match.Success returns false. Why does it return false? Thanks.


As Markus indicated, if you want it to match regardless of where the double is in the string, simply remove that ^ which indicates that it is checking the start of the string: -?\d+(?:\.\d+)? (Note that this may result in more than one match.)

If you want it to match only when the string ends in the double, add a $ to the end: -?\d+(?:\.\d+)?$

Online regex validators are incredibly useful, and some will break down which each individual component does. It's a lot faster to test out a regex this way instead of recompiling repeatedly until you get it right.

This is one of many.

EDIT: As Wiktor pointed out, this site doesn't actually validate .NET syntax regex. Therefore, it may not be suitable for certain types of regular expressions, but many common scenarios will be identical.