简体   繁体   中英

Regular expression for decimals that are accepted in decimal.Parse

The desired result is a pattern for positive inputs that doesn't throw an exception in decimal.Parse and doesn't accept the 01 -model-like inputs.

Valid inputs:

1
1.2
.2
1.

Invalid inputs:

01
01.2
.
1.B
A.2
A
A.

I liked the pattern in this answer ( -?(0|([1-9]\\d*))(\\.\\d+)? ); but somehow (as mentioned in the comment), it accepts X.2 (only with Regex.IsMatch ) and negative decimals, and rejects 1. ; so I modified it to /((0|([1-9]\\d*))(\\.\\d*)?)|(\\.\\d+)/g , and it worked perfectly in regexr.com and also RegExr v1 ; but I got no luck with Regex.IsMatch .

Any suggestions? and why doesn't the pattern work with Regex.IsMatch while it works somewhere else?

This passes all your tests:

var reg = new Regex("^(([1-9]*[0-9](\\.|(\\.[0-9]*)?))|(\\.[0-9]+))$");

(reg.IsMatch("1") == true).Dump();
(reg.IsMatch("1.2") == true).Dump();
(reg.IsMatch(".2") == true).Dump();
(reg.IsMatch("1.") == true).Dump();

(reg.IsMatch("01") == false).Dump();
(reg.IsMatch("01.2") == false).Dump();
(reg.IsMatch(".") == false).Dump();
(reg.IsMatch("1.B") == false).Dump();
(reg.IsMatch("A.2") == false).Dump();
(reg.IsMatch("A") == false).Dump();
(reg.IsMatch("A.") == false).Dump();

Explanation:

We try to capture as many 1-9 numbers as we can. This excludes leading 0s. We then allow any number before the decimal point.

Then we have three cases: No decimal point, a decimal point, a decimal point with numbers following it.

Otherwise, if we start with a decimal point, we allow any number, but at least one after it. This excludes .

You've to remove '/' character at the beginning. Since it's the syntax of regular expression to specify the start of regex in Javascript/ECMAScript but not c#.(Refer: What does the forward slash mean within a JavaScript regular expression? ) Thus, final regex is

((0|([1-9]\d*))(\.\d*)?)|(\.\d+)/g

在此处输入图片说明

I guess this simple regex should do the job perfectly well /-?(0?\\.\\d+|[1-9]\\d*\\.?\\d*)/g

You haven't asked for it but it also handles the negatives. If not needed just delete the -? at the beginning and make it even more simpler.

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