First of all, the character .
is called a dot, or period, or full stop, or decimal point, while a comma is the character: ,
.
Second, you can designate a digit in regex in a character class: [0-9]
means any digit between 0 to 9.
A dot in regex will match any character, so you need to escape it by means of a backslash (or putting it in a character class).
Remember though that the elements in the same character class can be in any order, so that if you want to get something having digits and a dot and use [0-9.]
it will match any digit, or a dot.
Now, you will need finite quantifiers for your task, which are designated by braces in the form of {m,n}
where m
is the minimum and n
the maximum. If you now use... [0-9.]{1,15}
it would mean the character class [0-9.]
repeated 1 up to 15 times.
But if you use [0-9.]{1,15}
, it will also match ......
or 1234
(remember I said earlier that the order did not matter.
So, applying all this, you get the regex:
[0-9]{1,15}\.[0-9]{1,3}
Now, since you are doing a validation, you will need anchors to specify that the regex should test the whole string (instead of simply finding a match).
^[0-9]{1,15}\.[0-9]{1,3}$
Last, since you can have optional decimals, you will have to use a group and the quantifier ?
which means 0 or 1:
^[0-9]{1,15}(?:\.[0-9]{1,3})?$
In your code, you will create the regex a bit like this:
string myString = "123456789.123";
var regexp = new Regex(@"^[0-9]{1,15}(?:\.[0-9]{1,3})?$");
var setMatches = regexp.Matches(myString);
foreach (Match match in setMatches)
{
Console.WriteLine(match.Groups[0].Value);
}
This will output the decimal if it passed the regex.
Or something like this:
string myString = "123456789.123";
Match match = Regex.Match(myString, @"^[0-9]{1,15}(?:\.[0-9]{1,3})?$");
if (match.Success)
{
Console.WriteLine(match.Groups[0].Value);
}