Regex for decimal validation [19,3]

I want to check the decimal number ( decimal[19,3] ). I used this

 @"[\d]{1,16}|[\d]{1,16}[\.]\d{1,3}" 

but it didn’t work.

Valid values ​​are as follows:

 1234567890123456.123 1234567890123456.12 1234567890123456.1 1234567890123456 1234567 0.0 .1 
+6
source share
5 answers

Relief:

\d must not be in [] . Use [] only if you want to check if a character is one of several characters or character classes.

. no escaping inside [] - [\.] , just permits . , but including \ in the string instead . may be language dependent (?). Or you can just take it out of [] and save it with shielding.

So we get:

 \d{1,16}|\d{1,16}\.\d{1,3} 

(which can be shortened using the optional / "once or not at all" quantifier ( ? )
to \d{1,16}(\.\d{1,3})? )

Corrections:

You probably want to make the second \d{1,16} optional or, equivalently, just make it \d{0,16} , so something like .1 possible:

 \d{1,16}|\d{0,16}\.\d{1,3} 

If something like 1. should also be allowed, you need to add optional . in the first part:

 \d{1,16}\.?|\d{0,16}\.\d{1,3} 

Edit: I was under the show [\d] , which matches \ or d , but actually matches the \d character class (fixed above).

+8
source

This will fit your 3 scenarios

 ^(\d{1,16}|(\d{0,16}\.)?\d{1,3})$ 

first part: a number from 0 to 16 digits

second: a number from 0 to 16 digits from 1 to 3 decimal places

third: nothing before the point, and then 1 to 3 decimal places

^ and $ are anchor points that correspond to the beginning of a line and the end of a line, so if you need to look for numbers inside lines of text, you should delete them.

Testdata:

enter image description here

Usage in C #

 string resultString = null; try { resultString = Regex.Match(subjectString, @"\d{1,16}\.?|\d{0,16}\.\d{1,3}").Value; } catch (ArgumentException ex) { // Syntax error in the regular expression } 

Minor optimization

A slightly more complicated regular expression, but it would be a little more correct to have the ?: Notation in the inner group, if you do not use it, to make this group without capture, for example:

 ^(\d{1,16}|(?:\d{0,16}\.)?\d{1,3})$ 
+2
source

The following regex will help you -

 @"^(\d{1,16}(\.\d{1,3})?|\.\d{1,3})$" 
+1
source

Try something like this

 (\d{0,16}\.\d{0,3})|(\d{0,16}) 

It works with all your examples.

to change. a new version;)

0
source

You can try:

 ^\d{0,16}(?:\.|$)(?:\d{0,3}|)$ 

matches from 0 to 16 digits then match the dot or end of the line and then match another 3 digits

-1
source

Source: https://habr.com/ru/post/946409/


All Articles