简体   繁体   中英

Limit the number of decimal and length of number with regex in c#

I have been trying to validate a number that limits the decimal point to 3 points and the length of the number (including the dot) to 6, but couldn't get it to validate properly. This is so far what I have:

^([0-9]([.][0-9]{1,3})?){1,6}$

How could I change the regex above to validate properly? Thanks.

You can use this lookahead based regex for checking length:

^(?=[0-9.]{1,6}$)[0-9]+(?:\.[0-9]{1,3})?$

RegEx Demo

For the total length I would just check the string length:

if(s.Length <= 6 && Regex.IsMatch(s, @"^[0-9]+(\.[0-9]{1,3})?$")) {

}

Because the {1,6} at the end of your expression means 0 to 6 repetitions of the term preceeding it (in your case, the whole number). It does not limit the length of the string.

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