I'm looking for a regex pattern that would match a version number.
The solutions I found here don't really match what I need.
I need the pattern to be valid for single numbers and also for numbers followed by .
The valid numbers are
1
1.23
1.2.53.4
Invalid numbers are
01
1.02.3
.1.2
1.2.
-1
Consider:
^[1-9]\d*(\.[1-9]\d*)*$
Breaking that down:
^ - Start at the beginning of the string.
[1-9] - Exactly one of the characters 1 thru 9.
\d* - More digits.
( - Beginning of some optional extra stuff
\. - A literal dot.
[1-9] - Exactly one of the characters 1 thru 9.
\d* - More digits.
) - End of the optional extra stuff.
* - There can be any number of those optional extra stuffs.
$ - And end at the end of the string.
Beware
Some of this syntax differs depending what regex engine you are using. For example, are you using the one from Perl, PHP, Javascript, C#, MySQL...?
In my experience, version numbers do not fit the neat format you described.
Specifically, you get values like 0.3RC5, 12.0-beta6, 2019.04.15-alpha4.5, 3.1stable, V6.8pl7 and more.
If you are validating existing data, make sure that your criteria fit the conditions you've described. In particular, if you are following "Semantic Versioning", be aware that versions which are zeros are legal, so 1.0.1, that "Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format.", and that "1" is not a legal version number.
Be warned that the above will also match stupidly long version numbers like 1.2.3.4.5.6.7.8.9.10.11.12.13.14. To prevent this, you can restrict it, like so:
^[1-9]\d*(\.[1-9]\d*){0,3}$
This changes the * for "any number of optional extra dots and numbers" to a range from zero to three. So it'd accept 1, 1.2, 1.2.3, and 1.2.3.4, but not 1.2.3.4.5.
Also, if you want zeros to be legal but only if there are no other numbers (so 0.3, 1.0.1), then it gets a little more complex:
^(0|[1-9]\d*)(\.(0|[1-9]\d*)){0,3}$
This question may also be a duplicate: A regex for version number parsing
Major.Minor.Patch - npm version like 0.1.2:
^([1-9]\d*|0)(\.(([1-9]\d*)|0)){2}$
More or optional minor groups like 1.1.5.0 or just 1.2:
^([1-9]\d*|0)(\.(([1-9]\d*)|0)){0,3}$
Avoid leading zero - no |0 in first group:
^([1-9]\d*)(\.(([1-9]\d*)|0)){0,3}$
Semantic Version String like 1.0.0-beta
^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$
Break down:
^: match the line start
$: match the line end
( and ): make a group
([1-9]\d*|0): match version number
[1-9]\d*: starting with 1~9, following any number of digit
|: logical or
0: literal zero
\.: literal (escaped) dot
{2}: exact 2 matches
{0,3}: 0~3 matches
Test cases (regex101 JavaScript):
Match:
0.0.0
0.0.1
0.1.0
1.0.0
1.0.1
1.1.0
1.1.1
0.0.10
0.10.0
10.0.0
0.1.10
1.0.10
1.0.100
0.100.1
100.0.0
1.20.0
Not match:
0.0.00
0.00.0
00.00.0
0.0.01
0.01.0
01.0.0
0.01.0
01.0.0
00.0.01
This regex should help:
^(([1-9]+\d*\.)+[1-9]+\d*)|[1-9]+\d*$
Below is the explanation.
[1-9]+\d* means a sequence which begins with a non-zero number, followed by zero or more numbers
The first part (([1-9]+\d*\.)+[1-9]+\d*) catches all of your correct examples, except of 1. So, we have a | (or), followed by a [1-9]+\d* sequence.
([\*,\^])([\-,\*,\w]+[\.])+(\w)*
for npm package fro example
"cross-env": "^5.2.0",
I need to only accept input that meets these rules...
0.25-24
Increments of .25 (.00, .25, .50, .75)
First digit doesn't have to be required.
Would like trailing zeros to be optional.
Examples of some valid entries:
0.25
.50
.5
1
1.0
5.50
23.75
24 (max allowed)
UPDATE: nothing at all, null/blank, should also be accepted as valid
Example of some invalid entries:
0
.0
.00
0.0
0.00
24.25
-1
I understand that RegEx is a pattern matching language therefore it's not great for ranges, less-than, and great-than checking. So to check if it's less than or equal to 24 means I'd have to find a pattern, right? So there are 24 possible patters which would make this a long RegEx, am I understanding this correctly? I could use ColdFusion to do the check to make sure it's in the 0-24 range. It's not the end of the world if I have use ColdFusion for this part, but it'd be nice to get it all into the RegEx if it doesn't cause it to be too long. This is what I have so far:
^\d{0,2}((\.(0|00|25|5|50|75))?)$
http://regex101.com/r/iS7zM3
This handles pretty much all of it except for the 0-24 range check or the check for just a zero. I'll keep plugging away at it but any help would be appreciated. Thanks!
Change \d{0,2} to (?:1[0-9]?|2[0-4]?|[3-9])? and it'll match from 1 to 24 (or nothing).
You can also simplify the second part to (?:\.(?:00?|25|50?|75))? - you could go further to (?:\.(?:[05]0?|[27]5))? but that might obfuscate the intent a bit too far.
To exclude 24.25 you could perhaps use a negative lookahead (?!24\.[^0]) to prevent anything other than 24.0 or 24.00, but it's probably simpler to just exclude 24 from the main pattern and include a specific check for 24/24.0/24.00 at the start:
(?x)
# checks for 24
^24$|^24\.00?$
|
# integer part
^
(?:1[0-9]?|2[0-3]?|[3-9]|0(?=\.[^0])|(?=\.[^0]))
# decimal part
(?:\.(?:00?|25|50?|75))?
$
That also includes a check for 0(?=\.[^0]) which uses a positive lookahead to only allow an initial 0 if the next char is a . followed by a non-zero (so 0.0 and 0.00 isn't allowed).
The (?x) flag allows whitespace to be ignored, allowing readable regex in your code - obviously preferable to squashing it all onto a single line - and also enables the use of # to start line comments to explain parts of a pattern. (Literal whitespaces and hashes can be escaped with backslash, or encoded via e.g. \x23 for hash.)
For comparison, here's a pure-CFML way of doing it:
IsNumeric(Num)
AND Num GT 0
AND Num LTE 24
AND NOT find('.',Num*4)
Now, are you really sure it's better as a regex...
You could try this regex (broken down):
^
(?:
(?:[1-9]|1\d|2[0-3])(?:\.(?:[05]0?|[27]5))? # Non-zeros with optional decimal
|
0?(?:\.(?:50?|[27]5)) # Decimals under 1
|
24(?:\.00?)? # The maximum
)
$
In one line:
^(?:(?:[1-9]|1\d|2[0-3])(?:\.(?:[05]0?|[27]5))?|0?(?:\.(?:50?|[27]5))|24(?:\.00?)?)$
regex101 demo
^([0-1]?[0-9]|2[0-4])((\.(0|00|25|5|50|75))?)$
This means the one's place can be 0-9 if the tens place is missing, a 0, or 1.
If the tens place is a 2, then the ones place can be 0-4.
The second part is great, it's simple and readable too. It has an extra set of parens though that can be removed, reducing it to this:
^([0-1]?[0-9]|2[0-4])(\.(0|00|25|5|50|75))?$
I am having a bit of difficulty with the following:
I need to allow any positive numeric value up to four decimal places. Here are some examples.
Allowed:
123
12345.4
1212.56
8778787.567
123.5678
Not allowed:
-1
12.12345
-12.1234
I have tried the following:
^[0-9]{0,2}(\.[0-9]{1,4})?$|^(100)(\.[0]{1,4})?$
However this doesn't seem to work, e.g. 1000 is not allowed when it should be.
Any ideas would be greatly appreciated.
Thanks
To explain why your attempt is not working for a value of 1000, I'll break down the expression a little:
^[0-9]{0,2} # Match 0, 1, or 2 digits (can start with a zero)...
(\.[0-9]{1,4})?$ # ... optionally followed by (a decimal, then 1-4 digits)
| # -OR-
^(100) # Capture 100...
(\.[0]{1,4})?$ # ... optionally followed by (a decimal, then 1-4 ZEROS)
There is no room for 4 digits of any sort, much less 1000 (theres only room for a 0-2 digit number or the number 100)
^\d* # Match any number of digits (can start with a zero)
(\.\d{1,4})?$ # ...optionally followed by (a decimal and 1-4 digits)
This expression will pass any of the allowed examples and reject all of the Not Allowed examples as well, because you (and I) use the beginning-of-string assertion ^.
It will also pass these numbers:
.2378
1234567890
12374610237856987612364017826350947816290385
000000000000000000000.0
0
... as well as a completely blank line - which might or might not be desired
to make it reject something that starts with a zero, use this:
^(?!0\d)\d* # Match any number of digits (cannot "START" with a zero)
(\.\d{1,4})?$ # ...optionally followed by (a decimal and 1-4 digits)
This expression (which uses a negative lookahead) has these evaluations:
REJECTED Allowed
--------- -------
0000.1234 0.1234
0000 0
010 0.0
You could also test for a completely blank line in other ways, but if you wanted to reject it with the regex, use this:
^(?!0\d|$)\d*(\.\d{1,4})?$
Try this:
^[0-9]*(?:\.[0-9]{0,4})?$
Explanation: match only if starting with a digit (excluding negative numbers), optionally followed by (non-capturing group) a dot and 0-4 digits.
Edit: With this pattern .2134 would also be matched. To only allow 0 < x < 1 of format 0.2134, replace the first * with a + above.
This regex would do the trick:
^\d+(?:\.\d{1,4})?$
From the beginning of the string search for one or more digits. If there's a . it must be followed with atleast one digit but a maximum of 4.
^(?<!-)\+?\d+(\.?\d{0,4})?$
The will match something with doesn't start with -, maybe has a + followed by an integer part with at least one number and an optional floating part of maximum 4 numbers.
Note: Regex does not support scientific notation. If you want that too let me know in a comment.
Well asked!!
You can try this:
^([0-9]+[\.]?[0-9]?[0-9]?[0-9]?[0-9]?|[0-9]+)$
If you have a double value but it goes to more decimal format and you want to shorter it to 4 then !
double value = 12.3457652133
value =Double.parseDouble(new DecimalFormat("##.####").format(value));
I need a regular expression to match all numbers inclusive between -100 and 0.
So valid values are:
0
-100
-40
Invalid are:
1
100
40
Thank you!
Use this function:
/^(?:0|-100|-[1-9]\d?)$/
OK, so I'm late, but here goes:
(?: # Either match:
- # a minus sign, followed by
(?: # either...
100 # 100
| # or
[1-9]\d? # a number between 1 and 99
)
| # or...
(?<!-) # (unless preceded by a minus sign)
\b0 # the number 0 on its own
)
\b # and make sure that the number ends here.
(?!\.) # except in a decimal dot.
This will find negative integer numbers (-100 to -1) and 0 in normal text. No leading zeroes allowed.
If you already have the number isolated, then
^(?:-(?:100|[1-9]\d?)|0)$
is enough if you don't want to allow leading zeroes or -0.
If you don't care about leading zeroes or -0, then use
^-?0*(?:100|\d\d?)$
...Now what do you do if your boss tells you "Oh, by the way, from tomorrow on, we need to allow values between -184.78 and 33.53"?
How about using a capture group and then programmatically testing the value e.g.
(-?\p{Digit}{1,3})
and then testing the captured value to ensure that it is within your range?
Try ^(-[1-9][0-9]?|-100|0)$
But perhaps it would be simpled to cast it to numeric and quickly check the range then
I'm new to regular expressions would this work?
(-100|((-[1-9]?[0-9])|\b0))
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" />