简体   繁体   中英

How would be this scientific notation regular expression in C#?

I'm using this regular expression for a scientific notation and setting to REGEX class in C#.

[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?

But it's not really working.

An alternative that's likely easier:

double.TryParse(stringInput, out doubleOutput);

Double.TryParse handles scientific notation by default.

What's not working about it?

One potential problem I see is that you're allowing leading 0s, and also trailing 0s in the decimal. Not sure if you want either, both, or neither. You should also make the decimal portion optional, but dependent on the existence of the decimal point. Here's what I'd recommend:

[-+]?(0?|[1-9][0-9]*)(\.[0-9]*[1-9])?([eE][-+]?(0|[1-9][0-9]*))?

That will match:

0
0.1
0.01
1
1.1
1.01
10
10.1
10.01
1e1
1
1e0
1E1
1e10

It won't match:

.
01
1.0
1.10
1e01

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