Reputation: 7164
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.
Upvotes: 0
Views: 1283
Reputation: 68
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.
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.
Upvotes: 4
Reputation: 81
Try this code sure it will work
using System.Text.RegularExpressions;
string txt = "I got 93.86 percentage";
string re1 = "(\\d+)"; // Integer Number 1
string re2 = "(\\.)"; // Any Single Character 1
string re3 = "(\\d+)"; // Integer Number 2
Regex r = new Regex(re1 + re2 + re3, RegexOptions.IgnoreCase | RegexOptions.Singleline);
Match m = r.Match(txt);
if (m.Success)
{
String int1 = m.Groups[1].ToString();
String c1 = m.Groups[2].ToString();
String int2 = m.Groups[3].ToString();
double dblResult = Convert.ToDouble(int1 + c1 + int2);
}
Upvotes: 4