Regex validator not working as expected - c#

Updated
I need to validate numbers, with decimal separator as , (comma) but this is not working:
validate.ValidationExpression = #"^[1-9]\d*(,\d+)?$";
123,01; 0,01; 0,001; 123456789,01 these are the numbers I would like to allow
Any help will be appreciated.

How about this:
^\d+(,\d+)?$
Visual explanation:
http://www.regexper.com/#%5E%5Cd%2B(%2C%5Cd%2B)%3F%24
That will:
^ Start at the beginning of a line
\d+ Find at least one, but as many as possible digits
( Start of a group
, The decimal sign
\d+ Find at least one, but as many as possible digits
) End of the group
? Makes the entire group optional
$ End of the line
This should capture integers and decimal numbers alike.
Try it out here:
http://regexr.com/398q6

That should do the work
^[-+]?[0-9]*,?[0-9]+$
It validates all of your examples and it supports negative numbers and numbers without any floating part.

If you want all your numbers to be accepted (123,01; 0,01; 0,001; 123456789,01) you have to change the first number 1 to 0, like this:
validate.ValidationExpression = #"^[0-9]\d*(,\d+)?$";
since you are basicly saying that any number 1-9 followed by , and 0-9 are fine so it wont select the ones that has a 0 before the ,.

validate.ValidationExpression = #"^\d+[,]?\d*$";
this will accept both 90 and 90,000

Related

Repeating pattern matching with Regex

I am trying to validate an input with a regular expression. Up until now all my tests fail and as my experience with regex is limited I thought someone might be able to help me out.
Pattern: digit (possibly "," digit) (possibly ;)
A String may not begin with a ; and not end with a ;.
Digits are allowed to stand alone or with
My regEx (not working): ((\d)(,\d)?)(;?) the problem is it does not seem to check until the end of the string. Also the optional parts are giving me headaches.
Update: ^[0-9]+(,[0-9])?(;[0-9]+(,[0-9])?)+$this seems to work better but it does not match the single digit.
OK:
2,3;4,4;3,2
2,3
2
2,3;3;4,3
NOK:
2,3,,,,
2,3asfafafa
;2,3
2,3;;3,4
2,3;3,4;
Your ^[0-9]+(,[0-9])?(;[0-9]+(,[0-9])?)+$ regex matches 1 or more digits, then an optional sequence of , and 1 digit, followed with one or more similar sequences.
You need to match zero or more comma-separated numbers:
^\d+(?:,\d+)?(?:;\d+(?:,\d+)?)*$
^
See the regex demo
Now, tweaking part:
If only single-digit numbers should be matched, use ^\d(?:,\d)?(?:;\d(?:,\d)?)*$
If the comma-separated number pairs can have the second element empty, add ? after each ,\d (if single digit numbers are to be matched) or * (if the numbers can have more than one digit): ^\d(?:,\d?)?(?:;\d(?:,\d?)?)*$ or ^\d+(?:,\d*)?(?:;\d+(?:,\d*)?)*$.

Regex Pattern to Validate Text Input With Max Value and Max Decimal Place

I need to create a pattern for a "text" type input to only allow a number from 0 to a specific max value and at the same time and validate to a specific number of decimal places.
Quick example:
Max Value = 300.86
Max Decimal Places = 3
Valid inputs:
0
1
300
300.86
300.85
300.850
300.851
.2
0.3333
Invalid inputs:
-1
301
300.87
300.861
1,30.2
1,.0
,.1
Currently I only know how to validate number of decimal places using this pattern:
^[,0-9]*(.\d{1,{0}})?$
Note:
I can't use type=number because I can't use any pattern with that :(
please help
I think something like this, is what you're after:
^(300(?:\.(?:[0-7]\d{0,2}|8(?:[0-5]\d?|60?)?))?|[0-2]?\d{0,2}(?:\.\d{0,3})?)$
See it here at REGEX STORM.
(Had to tweak it there, to end in \r, because REGEX STORM wouldn't match $ with end of line even though multi-line was selected???)
Explanation
It has two parts. The latter [0-2]?\d{0,2}(?:\.\d{0,3})? test for numbers below 300. It optionally starts with 0, 1 or 2 ([0-2]?). Then any two digits can follow (\d{0,2}). Then, optionally, it's followed by a . which, if present, can be followed by up to three digits (decimals) ((?:\.\d{0,3})?).
The first part - 300(?:\.(?:[0-7]\d{0,2}|8(?:[0-5]\d?|60?)?))? - test for when the integer part is exactly 300. It may then optionally be followed by a decimal point, and one out of three cases:
[0-7]\d{0,2} a digit in the range 0 to 7, followed by up to two digits
8(?:[0-5]\d*|60*)? an 8 followed by a digit in the range 0 to 5, optionally followed by a digit (The [0-5]\d? alternation).
or the number 86 and an optionall 0 (the 60? alternation)
These parts are in a capturing group separated by an alternation - |. The whole expression must be at the start of the string (^) (or line with multi-line flag) and at the end of the same ($).
Edit
Done some tweaking 'cause some numbers wrongly failed.
Edit 2
Completely missed "the maximum number of decimals" part. Fixed. (Fooled by the "valid" example 0.3333)
I don't know anything about C# so I'll just have to assume that what I can do in Python, you can find some way to do in C#. I'll give you my suggestion in pseudocode (this is not meant to mirror Python).
maxValue = some number
nDecimals = some number
givenValue = text with some number to be tested
#split number on decimal; remove non-digit characters from each side
leftSideOfDecimal = Replace(pattern = '^(\d{1,3}(,\d{3})*)(\.\d*)$', replacement = '\1', givenValue)
leftSideOfDecimal = Replace(',', '', leftSideOfDecimal)
rightSideOfDecimal = Replace('^(\d{1,3}(,\d{3})*)(\.\d*)$', '\3', givenValue)
rightSideOfDecimal = Replace('\.','',rightSideOfDecimal)
leftSideOfDecimal = pass leftSideOfDecimal to function to change type from text to integer
if leftSideOfDecimal <= maxValue and numberOfCharacters(rightSideOfDecimal) == nDecimals:
do whatever you want
Alternatively, if you have a function by which you can split strings on a given character (like a decimal or comma), then you just split the input on the decimal, clean up the first side as in the code, and then proceed with the last three lines of the code above. That way would save you from having to use a mildly complicated regex.

Regular expression in C# for Number with Decimal Point & Commas

I need to enter amount in a textbox which allows numbers with decimal point and commas.
What is the regular expression for this?
I used the below
txtInitialAmountGuarDetails.ValidationSettings.RegularExpression.ValidationExpression
= #"^[-+]?\d*[0-9](|.\d*[0-9])(|,\d*[0-9])?$";
But it not working for large numbers like 300,000,000,000,000.
Build it up piecemeal. Given a US locale, a number with these rules has in order:
The string beginning: ^
An optional sign: [+-]?
Up to 3 digits: \d{1,3}
A comma followed by 3 digits, repeated any number of times: (?:,\d{3})*
An optional decimal point and decimal part: (?:[.]\d+)?
The string end: $
Do you have restrictions on the number of digits after the decimal point? Then change the last plus sign to {2} for 2 digits.
So, the regex is:
#"^[+-]?\d{1,3}(?:,\d{3})*(?:[.]\d+)?$"
Or, if you want to explain your work, use the x option and:
#"(?x) # Extended format.
^[+-]? # Optional sign.
\d{1,3} # Initial 1-3 digits.
(?:,\d{3})* # Any number of commas followed by 3 digits.
(?:[.]\d+)?$" # An optional decimal point followed by any number of digits.
But does C# have a locale-dependent validator already?
I have not run it, but you can try it out.
var regexp =/^\s*?([\d\,]+(\.\d{1,2})?|\.\d{1,2})\s*$/;
This works: \d{1,3}(,\d{3})*\.{0,1}(\d{3},)*\d{0,3}
As for the after the comma issue, any choice should be fine. If you go with commas, my regex works. If you do 5 digits then a space just replace the end with (\d{5}\s{1})*\d{0,5}. And ofcourse if you just dont use any deliminator after the decimal you just put \d*
You can try this regex too:
^([+-]?\d{1,3}(?:,\d{1,3})*(?:\.\d+)*)$
Keep in mind . has a specific meaning in regex engine so it is necessary to escape it.
I would also suggest you to not use regex for this task instead look at masked textbox.
try this one:
^([0-9]{3}[,.]|)+[0-9]{0,3}$
let me know if it needs any enhancements...

Regex to allow values 1 to 100 with some conditions

i want a regex to allow 1-3 digits whole number,it should not start with 0 and should be a whole number,not decimals or fractions or any signed values,
this is what i have tried
"/^(\s*|\d{1,3})$/"
but it does not seem to work..
thanks in advance
You can do it like this:
^(([1-9]\d?)|100)$
This would ensure that
There is at least one digit
That multi-digit numbers start in a digit other than zero
That the only allowed three-digit number is 100.
^[1-9][0-9]\{,2\}$
It should be indeed end of line; end-of word will get the fractional part.

Discount mask with regex

Is it possible to create a 'dynamic' discount mask that takes % or numbers as discount values? What is the simple way to do this?
the samples of valide input: -25% or 0.25 or -5$ not 0 and two digit after dot
Try
#"(\+|-)?(\d+(\.\d*)?|\.\d+)%?"
It will find:
123.23
12.4%
.34
.34%
45.
45.%
8
7%
34
34%
+2.55%
-1.75%
UPDATE
and with ...
#"(\+|-)?(\d+(,\d{3})*(?!\d)(\.\d*)?|\.\d+)%?"
... you can include thousands separators as well.
I must confess that my second regex expression looks like a cat had walked accross my keyboard. Here the explanation
(\+|-)? optionally ? a plus or a minus sign.
\d+(,\d{3})*(?!\d)(\.\d*)? one or more digits \d+ followed by any number of thousands separators plus three digits (,\d{3})*, not followed by any digit (?!\d) in order to disallow four digits in sequence, optionally followed by a decimal point and any number of digits (\.\d*)?.
|\.\d+ or alternatively a decimal point followed by at least one digit.
%? finally an optional percent sign.
If I understand your question right, you want something like this:
#"^[+-]?(?:\d*\.)?\d+[%$]?$"
That's partly based on your example of -5$. Usually, though, the $ would go in front, so you'd want something like:
#"^(?:\$(?!.*%))?[+-]?(?:\d*\.)?\d+%?$"
That would allow $-5.00, 10, or +20%, but block $5%.
Edit:
Running with Olivier's idea of allowing commas:
#"^(\$(?!.*%))?[+-]?(\d{1,3}((,\d{3})*|\d*))?(\.\d+)?\b%?$"
Expanded to make it easier to understand:
#"^ #Require matching from the beginning of the line
(\$(?!.*%))? #Optionally allow a $ here, but only if there's no % later on.
[+-]? #Optionally allow + or - at the beginning
(
\d{1,3} #Covers the first three numerals
((,\d{3})*|\d*) #Allow numbers in 1,234,567 format, or simply a long string of numerals with no commas
)? #Allow for a decimal with no leading digits
(\.\d+)? #Optionally allow a period, but only with numerals behind it
\b #Word break (a sneaky way to require at least one numeral before this position, thus preventing an empty string)
%? #Optionally allow %
$" #End of line

Categories