2

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?

Community
  • 1
  • 1
Aly Elhaddad
  • 1,913
  • 1
  • 15
  • 31

3 Answers3

2

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 .

Rob
  • 26,989
  • 16
  • 82
  • 98
0

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

enter image description here

Community
  • 1
  • 1
M.S.
  • 4,283
  • 1
  • 19
  • 42
0

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.

Redu
  • 25,060
  • 6
  • 56
  • 76
  • I removed the `-?`; it returned `false` with all inputs mentioned in the question. – Aly Elhaddad Apr 02 '16 at 22:46
  • Please check it at http://regexr.com/3d4va with your inputs... With or without using `-?` in the front – Redu Apr 02 '16 at 23:13
  • The pattern mentioned in your comment works fine although it's different from that one in your answer; however, thanks for your effort. – Aly Elhaddad Apr 02 '16 at 23:48