Question

How could I extract a number of type double which may have exponent from a string with more character?

For example extract 56.8671311035e-06 from

"this is a string with a number inside 56.8671311035e-06 and the string continues here"

I guess it could be done using regular expressions, but my knowledge of them is very limited.

Was it helpful?

Solution

Yep, I'd say regular expressions are your friend here:

var match = Regex.Match(input, @"[0-9.]+e[-+][0-9]+");

Or you can prevent matching multiple decimal points with the following (the last one will be treated as the "proper" one):

@"\b[0-9]+(.[0-9]+)e[-+][0-9]+\b"

Edit: Here's a more complete one that will allow optional exponents and will also allow for the decimal point to be at the start of the number:

@"[\d]*\.?[\d]+(e[-+][\d]+)?"

OTHER TIPS

You can do this:

string test = "this is a string with a number inside 56.8671311035e-06 and the string continues here";
string expoNum = Regex.Match(test,@"[\d.]+e[-+]?\d+").Value;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top