Darf
Darf

Reputation: 2585

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.

Upvotes: 1

Views: 3228

Answers (2)

Asmor
Asmor

Reputation: 5181

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

Upvotes: 2

Austin Salonen
Austin Salonen

Reputation: 50235

An alternative that's likely easier:

double.TryParse(stringInput, out doubleOutput);

Double.TryParse handles scientific notation by default.

Upvotes: 5

Related Questions