Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for Regex validation decimal[19,3]

Tags:

regex

I want to validate a decimal number (decimal[19,3]). I used this

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

but it didn't work.

Below are valid values:

1234567890123456.123
1234567890123456.12
1234567890123456.1 
1234567890123456
1234567
0.0
.1
like image 448
Rushan Avatar asked Jun 03 '13 12:06

Rushan


2 Answers

Simplification:

The \d doesn't have to be in []. Use [] only when you want to check whether a character is one of multiple characters or character classes.

. doesn't need to be escaped inside [] - [\.] appears to just allow ., but allowing \ to appear in the string in the place of the . may be a language dependent possibility (?). Or you can just take it out of the [] and keep it escaped.

So we get to:

\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 simply make it \d{0,16}, so something like .1 is allowed:

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

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

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

Edit: I was under the impression [\d] matches \ or d, but it actually matches the character class \d (corrected above).

like image 127
Bernhard Barker Avatar answered Sep 18 '22 11:09

Bernhard Barker


This would match your 3 scenarios

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

first part: a 0 to 16 digit number

second: a 0 to 16 digit number with 1 to 3 decimals

third: nothing before a dot and then 1 to 3 decimals

the ^ and $ are anchorpoints that match start of line and end of line, so if you need to search for numbers inside lines of text, your should remove those.

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
}

Slight optimization

A bit more complicated regex, but a bit more correct would be to have the ?: notation in the "inner" group, if you are not using it, to make that a non-capture group, like this:

^(\d{1,16}|(?:\d{0,16}\.)?\d{1,3})$
like image 45
Jim Wolff Avatar answered Sep 20 '22 11:09

Jim Wolff