Regular expression accept custom numbers - regex

I need a help
How to change this regular expression that allows to accept positive numbers
like 0, 0.00, .02,etc.. ,
Now this accept 5 digits decimal that is greater than 0 and up to 100
"^100|(\d\d?)(\.(1[01]?|0\d?))?$"

First you should wrap the whole expression except the string boundaries in a group. Otherwise your expression would just say either start with … or end with … as the | has a higher precedence than ^ and $:
^(100|(\d\d?)(\.(1[01]?|0\d?))?)$
And now a solution to your question:
^((100|[1-9]?[0-9])(\.\d{1,2})?|\.\d{1,2})$

I am not sure in which language you are wishing to get the result but it seems quite simple.
The rules are input should start with either digit(s) or decimal point and then, either decimal point or digit(s).

Related

regular expression that accepts numbers like 1,000.10? [duplicate]

I need regex to validate a number that could contain thousand separators or decimals using javascript.
Max value being 9,999,999.99
Min value 0.01
Other valid values:
11,111
11.1
1,111.11
INVALID values:
1111
1111,11
,111
111,
I've searched all over with no joy.
/^\d{1,3}(,\d{3})*(\.\d+)?$/
About the minimum and maximum values... Well, I wouldn't do it with a regex, but you can add lookaheads at the beginning:
/^(?!0+\.00)(?=.{1,9}(\.|$))\d{1,3}(,\d{3})*(\.\d+)?$/
Note: this allows 0,999.00, so you may want to change it to:
/^(?!0+\.00)(?=.{1,9}(\.|$))(?!0(?!\.))\d{1,3}(,\d{3})*(\.\d+)?$/
which would not allow a leading 0.
Edit:
Tests: http://jsfiddle.net/pKsYq/2/
((\d){1,3})+([,][\d]{3})*([.](\d)*)?
It worked on a few, but I'm still learning regex as well.
The logic should be 1-3 digits 0-1 times, 1 comma followed by 3 digits any number of times, and a single . followed by any number of digits 0-1 times
First, I want to point out that if you own the form the data is coming from, the best way to restrict the input is to use the proper form elements (aka, number field)
<input type="number" name="size" min="0.01" max="9,999,999.99" step="0.01">
Whether "," can be entered will be based on the browser, but the browser will always give you the value as an actual number. (Remember that all form data must be validated/sanitized server side as well. Never trust the client)
Second, I'd like to expand on the other answers to a more robust (platform independent)/modifiable regex.
You should surround the regex with ^ and $ to make sure you are matching against the whole number, not just a subset of it. ex ^<my_regex>$
The right side of the decimal is optional, so we can put it in an optional group (<regex>)?
Matching a literal period and than any chain of numbers is simply \.\d+
If you want to insist the last number after the decimal isn't a 0, you can use [1-9] for "a non-zero number" so \.\d+[1-9]
For the left side of the decimal, the leading number will be non-zero, or the number is zero. So ([1-9]<rest-of-number-regex>|0)
The first group of numbers will be 1-3 digits so [1-9]\d{0,2}
After that, we have to add digits in 3s so (,\d{3})*
Remember ? means optional, so to make the , optional is just (,?\d{3})*
Putting it all together
^([1-9]\d{0,2}(,?\d{3})*|0)(\.\d+[1-9])?$
Tezra's formula fails for '1.' or '1.0'. For my purposes, I allow leading and trailing zeros, as well as a leading + or - sign, like so:
^[-+]?((\d{1,3}(,\d{3})*)|(\d*))(\.|\.\d*)?$
In a recent project we needed to alter this version in order to meet international requirements.
This is what we used: ^-?(\d{1,3}(?<tt>\.|\,| ))((\d{3}\k<tt>)*(\d{3}(?!\k<tt>)[\.|\,]))?\d*$
Creating a named group (?<tt>\.|\,| ) allowed us to use the negative look ahead (?!\k<tt>)[\.|\,]) later to ensure the thousands separator and the decimal point are in fact different.
I have used below regrex for following retrictions -
^(?!0|\.00)[0-9]+(,\d{3})*(.[0-9]{0,2})$
Not allow 0 and .00.
','(thousand seperator) after 3 digits.
'.' (decimal upto 2 decimal places).

Regular Expression to avoid negative values

I am totally new to creating my own regular expressions. I have one reg ex developed my team member as listed below
^\s*-?\d{1,3}(\.\d{1,4})?\s*$
This will ensure that the value entered is having a maximum of 3 digits and may or may not have a negative sign.
RegExp Calculator
If I test with a value, “-1000” it will say the entered value does not meet the requirements and an error will be shown to the user.
I need to modify the expression in such way that:
If a “-“ sign is there, it can have more than 3 digits and decimals. [But if the user enter a “-“ and any alphabets, it should not match ]
You could change it to this one :
^\s*(\d{1,3}|-\d+)(\.\d{1,4})?\s*$
The first part in the form (a|b) means a or b. It means that the part before the comma is either
1 to 3 digits
or - followed by at least one digit
Use |(OR) operator in regex
^(\d{1,3}([.]\d{1,4})?|-\d+([.]\d+)?)$
If you just want to validate if a number is between -999 and 999 please parse it to an Integer and check -999 < x < 999.

Regular Expression for a 0.25 interval

My aim is to write a regular expression for a decimal number where a valid number is one of
xx.0, xx.125, xx.25, xx.375, xx.5, xx.625, xx.75, xx.875 (i.e. measured in 1/8ths) The xx can be 0, 1 or 2 digits.
i have come up with the following regex:
^\d*\.?((25)|(50)|(5)|(75)|(0)|(00))?$
while this works for 0.25,0.5,0.75 it wont work for 0.225, 0.675 etc .
i assumed that the '?' would work in a case where there is preceding number as well.
Can someone point out my mistake
Edit : require the number to be a decimal !
Edit2 : i realized my mistake i was confused about the '?'. Thank you.
I would add another \d* after the literal . check \.
^\d*\.?\d*((25)|(50)|(5)|(75)|(0)|(00))?$
I think it would probably just be easier to multiply the decimal part by 8, but you don't consider digits that lead the last two decimals in the regex.
^\d{0,2}\.(00?|(1|6)?25|(3|8)?75|50?)$
Your mistake is: \.? indicates one optional \., not a digit (or anything else, in this case).
About the ? (question mark) operator: Makes the preceding item optional. Greedy, so the optional item is included in the match if possible. (source)
^\d{0,2}\.(0|(1|2|6)?25|(3|6|8)?75|5)$
Regular expressions are for matching patterns, not checking numeric values. Find a likely string with the regex, then check its numeric value in whatever your host language is (PHP, whatever).

regular expression allows only decimal to enter

^(0)?[0-9]{0,}((\.){1}[0-9]{0,2}){0,1}$
The above regular expression allows me to enter numbers upto 4 decimal places with an optional 0 before the decimal(.) point. But it is not throwing error when I'm not entering numbers after decimal like 0., 12.,etc. !!!
Any guidance on this.
This is because you allow between 0 and 2 digits after the ..
Since you said you wanted between 1 and 4 digits, you probably want this:
^[0-9]*(\.[0-9]{1,4})?$
Note, I have replaced {0,} with * and {0,1} with ? as they are equivalent.
In addition, I've removed the {1}, as it matches one time per default.
The initial (0)? is also a bit redundant.
Beware, this regular expression matches .50. If you want to ensure that a number exists before the decimal point, change the first * to a + like so:
^[0-9]+(\.[0-9]{1,4})?$
To further simplify the regular expression, you can also replace [0-9] with \d in most regular expression engines, giving you:
^\d+(\.\d{1,4})?$
This regex could be simplified to the following:
^\d*(\.\d{1,4})?$
You can see it in action here: http://regexr.com?2vamh

Decimal or numeric values in regular expression validation

I am trying to use a regular expression validation to check for only decimal values or numeric values. But user enters numeric value, it don't be first digit "0"
How do I do that?
A digit in the range 1-9 followed by zero or more other digits:
^[1-9]\d*$
To allow numbers with an optional decimal point followed by digits. A digit in the range 1-9 followed by zero or more other digits then optionally followed by a decimal point followed by at least 1 digit:
^[1-9]\d*(\.\d+)?$
Notes:
The ^ and $ anchor to the start and end basically saying that the whole string must match the pattern
()? matches 0 or 1 of the whole thing between the brackets
Update to handle commas:
In regular expressions . has a special meaning - match any single character. To match literally a . in a string you need to escape the . using \. This is the meaning of the \. in the regexp above. So if you want to use comma instead the pattern is simply:
^[1-9]\d*(,\d+)?$
Further update to handle commas and full stops
If you want to allow a . between groups of digits and a , between the integral and the fractional parts then try:
^[1-9]\d{0,2}(\.\d{3})*(,\d+)?$
i.e. this is a digit in the range 1-9 followed by up to 2 other digits then zero or more groups of a full stop followed by 3 digits then optionally your comma and digits as before.
If you want to allow a . anywhere between the digits then try:
^[1-9][\.\d]*(,\d+)?$
i.e. a digit 1-9 followed by zero or more digits or full stops optionally followed by a comma and one or more digits.
Actually, none of the given answers are fully cover the request.
As the OP didn't provided a specific use case or types of numbers, I will try to cover all possible cases and permutations.
Regular Numbers
Whole Positive
This number is usually called unsigned integer, but you can also call it a positive non-fractional number, include zero. This includes numbers like 0, 1 and 99999.
The Regular Expression that covers this validation is:
/^(0|[1-9]\d*)$/
Test This Regex
Whole Positive and Negative
This number is usually called signed integer, but you can also call it a non-fractional number. This includes numbers like 0, 1, 99999, -99999, -1 and -0.
The Regular Expression that covers this validation is:
/^-?(0|[1-9]\d*)$/
Test This Regex
As you probably noticed, I have also included -0 as a valid number. But, some may argue with this usage, and tell that this is not a real number (you can read more about Signed Zero here). So, if you want to exclude this number from this regex, here's what you should use instead:
/^-?(0|[1-9]\d*)(?<!-0)$/
Test This Regex
All I have added is (?<!-0), which means not to include -0 before this assertion. This (?<!...) assertion called negative lookbehind, which means that any phrase replaces the ... should not appear before this assertion. Lookbehind has limitations, like the phrase cannot include quantifiers. That's why for some cases I'll be using Lookahead instead, which is the same, but in the opposite way.
Many regex flavors, including those used by Perl and Python, only allow fixed-length strings. You can use literal text, character escapes, Unicode escapes other than \X, and character classes. You cannot use quantifiers or backreferences. You can use alternation, but only if all alternatives have the same length. These flavors evaluate lookbehind by first stepping back through the subject string for as many characters as the lookbehind needs, and then attempting the regex inside the lookbehind from left to right.
You can read more bout Lookaround assertions here.
Fractional Numbers
Positive
This number is usually called unsigned float or unsigned double, but you can also call it a positive fractional number, include zero. This includes numbers like 0, 1, 0.0, 0.1, 1.0, 99999.000001, 5.10.
The Regular Expression that covers this validation is:
/^(0|[1-9]\d*)(\.\d+)?$/
Test This Regex
Some may say, that numbers like .1, .0 and .00651 (same as 0.1, 0.0 and 0.00651 respectively) are also valid fractional numbers, and I cannot disagree with them. So here is a regex that is additionally supports this format:
/^(0|[1-9]\d*)?(\.\d+)?(?<=\d)$/
Test This Regex
Negative and Positive
This number is usually called signed float or signed double, but you can also call it a fractional number. This includes numbers like 0, 1, 0.0, 0.1, 1.0, 99999.000001, 5.10, -0, -1, -0.0, -0.1, -99999.000001, 5.10.
The Regular Expression that covers this validation is:
/^-?(0|[1-9]\d*)(\.\d+)?$/
Test This Regex
For non -0 believers:
/^(?!-0(\.0+)?$)-?(0|[1-9]\d*)(\.\d+)?$/
Test This Regex
For those who want to support also the invisible zero representations, like .1, -.1, use the following regex:
/^-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)$/
Test This Regex
The combination of non -0 believers and invisible zero believers, use this regex:
/^(?!-0?(\.0+)?$)-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)$/
Test This Regex
Numbers with a Scientific Notation (AKA Exponential Notation)
Some may want to support in their validations, numbers with a scientific character e, which is by the way, an absolutely valid number, it is created for shortly represent a very long numbers. You can read more about Scientific Notation here. These numbers are usually looks like 1e3 (which is 1000), 1e-3 (which is 0.001) and are fully supported by many major programming languages (e.g. JavaScript). You can test it by checking if the expression '1e3'==1000 returns true.
I will divide the support for all the above sections, including numbers with scientific notation.
Regular Numbers
Whole positive number regex validation, supports numbers like 6e4, 16e-10, 0e0 but also regular numbers like 0, 11:
/^(0|[1-9]\d*)(e-?(0|[1-9]\d*))?$/i
Test This Regex
Whole positive and negative number regex validation, supports numbers like -6e4, -16e-10, -0e0 but also regular numbers like -0, -11 and all the whole positive numbers above:
/^-?(0|[1-9]\d*)(e-?(0|[1-9]\d*))?$/i
Test This Regex
Whole positive and negative number regex validation for non -0 believers, same as the above, except now it forbids numbers like -0, -0e0, -0e5 and -0e-6:
/^(?!-0)-?(0|[1-9]\d*)(e-?(0|[1-9]\d*))?$/i
Test This Regex
Fractional Numbers
Positive number regex validation, supports also the whole numbers above, plus numbers like 0.1e3, 56.0e-3, 0.0e10 and 1.010e0:
/^(0|[1-9]\d*)(\.\d+)?(e-?(0|[1-9]\d*))?$/i
Test This Regex
Positive number with invisible zero support regex validation, supports also the above positive numbers, in addition numbers like .1e3, .0e0, .0e-5 and .1e-7:
/^(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?$/i
Test This Regex
Negative and positive number regex validation, supports the positive numbers above, but also numbers like -0e3, -0.1e0, -56.0e-3 and -0.0e10:
/^-?(0|[1-9]\d*)(\.\d+)?(e-?(0|[1-9]\d*))?$/i
Test This Regex
Negative and positive number regex validation fro non -0 believers, same as the above, except now it forbids numbers like -0, -0.00000, -0.0e0, -0.00000e5 and -0e-6:
/^(?!-0(\.0+)?(e|$))-?(0|[1-9]\d*)(\.\d+)?(e-?(0|[1-9]\d*))?$/i
Test This Regex
Negative and positive number with invisible zero support regex validation, supports also the above positive and negative numbers, in addition numbers like -.1e3, -.0e0, -.0e-5 and -.1e-7:
/^-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?$/i
Test This Regex
Negative and positive number with the combination of non -0 believers and invisible zero believers, same as the above, but forbids numbers like -.0e0, -.0000e15 and -.0e-19:
/^(?!-0?(\.0+)?(e|$))-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?$/i
Test This Regex
Numbers with Hexadecimal Representation
In many programming languages, string representation of hexadecimal number like 0x4F7A may be easily cast to decimal number 20346.
Thus, one may want to support it in his validation script.
The following Regular Expression supports only hexadecimal numbers representations:
/^0x[0-9a-f]+$/i
Test This Regex
All Permutations
These final Regular Expressions, support the invisible zero numbers.
Signed Zero Believers
/^(-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?|0x[0-9a-f]+)$/i
Test This Regex
Non Signed Zero Believers
/^((?!-0?(\.0+)?(e|$))-?(0|[1-9]\d*)?(\.\d+)?(?<=\d)(e-?(0|[1-9]\d*))?|0x[0-9a-f]+)$/i
Test This Regex
Hope I covered all number permutations that are supported in many programming languages.
Oh, forgot to mention, that those who want to validate a number includes a thousand separator, you should clean all the commas (,) first, as there may be any type of separator out there, you can't actually cover them all.
But you can remove them first, before the number validation:
//JavaScript
function clearSeparators(number)
{
return number.replace(/,/g,'');
}
Similar post on my blog.
I had the same problem, but I also wanted ".25" to be a valid decimal number. Here is my solution using JavaScript:
function isNumber(v) {
// [0-9]* Zero or more digits between 0 and 9 (This allows .25 to be considered valid.)
// ()? Matches 0 or 1 things in the parentheses. (Allows for an optional decimal point)
// Decimal point escaped with \.
// If a decimal point does exist, it must be followed by 1 or more digits [0-9]
// \d and [0-9] are equivalent
// ^ and $ anchor the endpoints so tthe whole string must match.
return v.trim().length > 0 && v.trim().match(/^[0-9]*(\.[0-9]+)?$/);
}
Where my trim() method is
String.prototype.trim = function() {
return this.replace(/(^\s*|\s*$)/g, "");
};
Matthew DesVoigne
I've tested all given regexes but unfortunately none of them pass those tests:
String []goodNums={"3","-3","0","0.0","1.0","0.1"};
String []badNums={"001","-00.2",".3","3.","a",""," ","-"," -1","--1","-.1","-0", "2..3", "2-", "2...3", "2.4.3", "5-6-7"};
Here is the best I wrote that pass all those tests:
"^(-?0[.]\\d+)$|^(-?[1-9]+\\d*([.]\\d+)?)$|^0$"
A simple regex to match a numeric input and optional 2 digits decimal.
/^\d*(\.)?(\d{0,2})?$/
You can modify the {0,2} to match your decimal preference {min, max}
Snippet for validation:
const source = document.getElementById('source');
source.addEventListener('input', allowOnlyNumberAndDecimals);
function allowOnlyNumberAndDecimals(e) {
let str = e.target.value
const regExp = /^\d*(\.)?(\d{0,2})?$/
status = regExp.test(str) ? 'valid' : 'invalid'
console.log(status + ' : ' + source.value)
}
<input type="text" id="source" />
Here is a great working regex for numbers. This accepts number with commas and decimals.
/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/
Here is my regex for validating numbers:
^(-?[1-9]+\\d*([.]\\d+)?)$|^(-?0[.]\\d*[1-9]+)$|^0$
Valid numbers:
String []validNumbers={"3","-3","0","0.0","1.0","0.1","0.0001","-555","94549870965"};
Invalid numbers:
String []invalidNumbers={"a",""," ","-","001","-00.2","000.5",".3","3."," -1","--1","-.1","-0"};
Below is the perfect one for mentioned requirement :
^[0-9]{1,3}(,[0-9]{3})*(([\\.,]{1}[0-9]*)|())$
Try this code, hope it will help you
String regex = "(\\d+)(\\.)?(\\d+)?"; for integer and decimal like 232 232.12
/([0-9]+[.,]*)+/ matches any number with or without coma or dots
it can match
122
122,354
122.88
112,262,123.7678
bug: it also matches 262.4377,3883 ( but it doesn't matter parctically)
if you need to validate decimal with dots, commas, positives and negatives try this:
Object testObject = "-1.5";
boolean isDecimal = Pattern.matches("^[\\+\\-]{0,1}[0-9]+[\\.\\,]{1}[0-9]+$", (CharSequence) testObject);
Good luck.
My regex
/^((0((\.\d*[1-9]\d*)?))|((0(?=[1-9])|[1-9])\d*(\.\d*[1-9]\d*)?))$/
The regular expression ^(\d+(\.\d+)?)$ works for every number.
For demonstration I embedded it into a runnable JS-fiddle:
const source = document.getElementById('source');
source.addEventListener('input', allowOnlyNumberAndDecimals);
function allowOnlyNumberAndDecimals(e) {
let str = e.target.value
const regExp = /^(\d+(\.\d+)?)$/
let status = regExp.test(str) ? 'valid' : 'invalid'
console.log(status + ' : ' + source.value)
}
body {
height: 100vh;
background: pink;
color: black;
justify-content: center;
align-items: center;
}
<h1>VALIDATE ALL NUMBERS :)<h1>
<input type="text" id="source" />