简体   繁体   中英

Extract double number value with exponent from text

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.

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]+)?"

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM