RegEx, either 0, 1-9.1-9 or 10.0? - regex

I require a RegEx that validates the entered number to be either
0
1-9 with one decimal (i.e. 5.5, but not 3.33 or 7)
10.0
I was trying with the below RegEx, but I'm not succeeding..
/(0|[1-9]\.[1-9]|\10.0)/g
fyi, in my system, a '0' means 'No grade entered', a 10.0 is the maximum and the minimum is a 1.0

You're having problems probably because you're missing the start and end markers, e.g., ^ and $, hence, your solution is not bounded to the whole input. Try:
/^(0|[1-9]\.[0-9]|10\.0)$/g

I think this one is more robust?
^0$|^[1-9]{1}\.[0-9]{1}$|^10\.0$
Main things to worry about are the above ones will for example match 12.0, because the 0 is not anchored. You also want to use {1} quantifiers in the decimal case, and include [0-9] after the decimal (so 7.0 is matched).
EDIT: Explanation of changes
Adding ^ and $ to each of the three options ensures that the match is the whole of the string. This means that for example, ^0$ matches 0 but does not match 0.0, 01, 6.0 or any other string where 0 is only part of the string.
Changing [1-9] after the decimal point in the second option to [0-9] allows 7.0 to be matched, where it previously would not
Adding the quantifiers {1} to the [] groups before and after the decimal point in the second option ensures that we match only a single digit. Previously, [1-9]\.[0-9] would match 12.1, 5.33 and other strings where the match is only contained within the string. They are somewhat redundant with ^ and $, but with regexes I like failsafes...
I also moved the escaping \ in the third option to be before the decimal point, which seemed like a typo (we want to match a literal . not use . to mean any character)

My proposal:
(?<![0-9.])(0|(?:[1-9]\.[0-9])|(?:10\.0))(?![0-9.])
All of the following will match: 0, 1.1, 1.0, 1.9, 2.0, 2.1, 9.0, 9.1, 9.9, 10.0, but all of the following will not: 0.1, 0.2, 0.9, 1.11, 1.20, 1.01, 10.05, 110.05. Does not require one-number per line, can extract numbers embedded in text.
Here is the example: regex101
More detailed explanation:
(?<![0-9.])
is a look-behind that prevents us from ripping out pieces of number-literals in multi-line input, e.g. 10000010.0 should not be matched.
(0|(?:[1-9]\.[0-9])|(?:10\.0))
This is the part that matches your specification. The ?: is needed only if you want to keep the matched groups "clean", in the sense that there will be no group(2) for the middle case
(?![0-9.])
This is another look ahead, again: important only for multi-line text.
If you drop look-behinds, look-aheads and "environmentally friendly match-groups", you end up with something like:
0|([1-9]\.[0-9])|(10\.0)
and if you are working with one-item-per-line input, you can add prefix ^ and suffix $, and go with that.

Related

Regex to enter a decimal number digit by digit

I have a requirement where user can input only between 0.01 to 100.00 in a textbox. I am using regex to limit the data entered. However, I cannot enter a decimal point, like 95.83 in the regex. Can someone help me fix the below regex?
(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{1,2})?)$
if I copy paste the value, it passes. But unable to type a decimal point.
Please advice.
Link to regex tester: https://regex101.com/r/b2BF6A/1
Link to demo: https://stackblitz.com/edit/react-9h2xsy
The regex
You can use the following regex:
See regex in use here
^(?:(?:\d?[1-9]|[1-9]0)(?:\.\d{0,2})?|0{0,2}\.(?:\d?[1-9]|[1-9]0)|10{2}(?:\.0{0,2})?)$
How it works
^(?:...|...|...)$ this anchors the pattern to ensure it matches the entire string
^ assert position at the start of the line
(?:...|...|...) non-capture group - used to group multiple alternations
$ assert position at the end of the line
(?:\d?[1-9]|[1-9]0)(?:\.\d{0,2})? first option
(?:\d?[1-9]|[1-9]0) match either of the following
\d?[1-9] optionally match any digit, then match a digit in the range of 1 to 9
[1-9]0 match any digit between 1 and 9, followed by 0
(?:\.\d{0,2})? optionally match the following
\. this character . literally
\d{0,2} match any digit between 0 and 2 times
0{0,2}\.(?:\d?[1-9]|[1-9]0) second option
0{0,2} match 0 between 0 and 2 times
\. match this character . literally
(?:\d?[1-9]|[1-9]0) match either of the following options
\d?[1-9] optionally match any digit, then match a digit in the range of 1 to 9
[1-9]0 match any digit between 1 and 9, followed by 0
10{2}(?:\.0{0,2})? third option
10{2} match 100
(?:\.0{0,2})? optionally match ., followed by 0 between 0 and 2 times
How it works (in simpler terms)
With the above descriptions for each alternation, this is what they will match:
Any two-digit number other than 0 or 00, optionally followed by any two-digit decimal.
In terms of a range, it's 1.00-99.99 with:
Optional leading zero: 01.00-99.99
Optional decimal: 01-99, or 01.-99, or 01.0-01.99
Any two-digit decimal other than 0 or 00
In terms of a range, it's .01-.99 with:
Optional leading zeroes: 00.01-00.99 or 0.01-0.99
Literally 100, followed by optional decimals: 100, or 100., or 100.0, or 100.00
The code
RegExp vs /pattern/
In your code, you can use either of the following options (replacing pattern with the pattern above):
new RegExp('pattern')
/pattern/
The first option above uses a string literal. This means that you must escape the backslash characters in the string in order for the pattern to be properly read:
^(?:(?:\\d?[1-9]|[1-9]0)(?:\\.\\d{0,2})?|0{0,2}\\.(?:\\d?[1-9]|[1-9]0)|10{2}(?:\\.0{0,2})?)$
The second option above allows you to avoid this and use the regex as is.
Here's a fork of your code using the second option.
Usability Issues
Please note that you'll run into a couple of usability issues with your current method of tackling this:
The user cannot erase all the digits they've entered. So if the user enters 100, they can only erase 00 and the 1 will remain. One option to resolving this is to make the entire non-capture group (with the alternations) optional by adding a ? after it. Whilst this does solve that issue, you now need to keep two regular expression patterns - one for user input and the other for validation. Alternatively, you could just test if the input is an empty string to allow it (but not validate the form until the field is filled.
The user cannot enter a number beginning with .. This is because we don't allow the input of . to go through your validation steps. The same rule applies here as the previous point made. You can allow it though if the value is . explicitly or add a new alternation of |\.
Similarly to my last point, you'll run into the issue for .0 when a user is trying to write something like .01. Again here, you can run the same test.
Similarly again, 0 is not valid input - same applies here.
An change to the regex that covers these states (0, ., .0, 0., 0.0, 00.0 - but not .00 alternatives) is:
^(?:(?:\d?[1-9]?|[1-9]0)(?:\.\d{0,2})?|0{0,2}\.(?:\d?[1-9]?|[1-9]0)|10{2}(?:\.0{0,2})?)$
Better would be to create logic for these cases to match them with a separate regex:
^0{0,2}\.?0?$
Usability Fixes
With the changes above in mind, your function would become:
See code fork here
handleChange(e) {
console.log(e.target.value)
const r1 = /^(?:(?:\d?[1-9]|[1-9]0)(?:\.\d{0,2})?|0{0,2}\.(?:\d?[1-9]|[1-9]0)|10{2}(?:\.0{0,2})?)$/;
const r2 = /^0{0,2}\.?0?$/
if (r1.test(e.target.value)) {
this.setState({
[e.target.name]: e.target.value
});
} else if (r2.test(e.target.value)) {
// Value is invalid, but permitted for usability purposes
this.setState({
[e.target.name]: e.target.value
});
}
}
This now allows the user to input those values, but also allows us to invalidate them if the user tries to submit it.
Using the range 0.01 to 100.00 without padding is this (non-factored):
0\.(?:0[1-9]|[1-9]\d)|[1-9]\d?\.\d{2}|100\.00
Expanded
# 0.01 to 0.99
0 \.
(?:
0 [1-9]
| [1-9] \d
)
|
# 1.00 to 99.99
[1-9] \d? \.
\d{2}
|
# 100.00
100 \.
00
It can be made to have an optional cascade if incremental partial form
should be allowed.
That partial is shown here for the top regex range :
^(?:0(?:\.(?:(?:0[1-9]?)|[1-9]\d?)?)?|[1-9]\d?(?:\.\d{0,2})?|1(?:0(?:0(?:\.0{0,2})?)?)?)?$
The code line with stringed regex :
const newRegExp = new RegExp("^(?:0(?:\\.(?:(?:0[1-9]?)|[1-9]\\d?)?)?|[1-9]\\d?(?:\\.\\d{0,2})?|1(?:0(?:0(?:\\.0{0,2})?)?)?)?$");
_________________________
The regex 'partial' above requires the input to be blank or to start
with a digit. It also doesn't allow 1-9 with a preceding 0.
If that is all to be allowed, a simple mod is this :
^(?:0{0,2}(?:\.(?:(?:0[1-9]?)|[1-9]\d?)?)?|(?:[1-9]\d?|0[1-9])(?:\.\d{0,2})?|1(?:0(?:0(?:\.0{0,2})?)?)?)?$
which allows input like the following:
(It should be noted that doing this requires allowing the dot . as
a valid input but could be converted to 0. on the fly to be put
inside the input box.)
.1
00.01
09.90
01.
01.11
00.1
00
.
Stringed version :
"^(?:0{0,2}(?:\\.(?:(?:0[1-9]?)|[1-9]\\d?)?)?|(?:[1-9]\\d?|0[1-9])(?:\\.\\d{0,2})?|1(?:0(?:0(?:\\.0{0,2})?)?)?)?$"

Regex pattern to match valid version numbers

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",

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 Range with decimal 0.1 - 7.0

I need a regular expression that should validate decimal point as well as range. Totally 3 number should be present including dot and the value must be greater than 0.0. That means the valid range is from 0.1 to 7.0.
I used the following regex: ^\\d{1,1}(\\.\\d{1,2})?$
It works fine except for the range validation. What do I need to change?
Regexes are notoriously bad at validating number ranges. But it's possible. You have to break down the number range into the expected textual representations of those numbers:
^ # Start of string
(?: # Either match...
7(?:\.0)? # 7.0 (or 7)
| # or
[1-6](?:\.[0-9])? # 1.0-6.9 (or 1-6)
| # or
0?\.[1-9] # 0.1-0.9 (or .1-.9)
) # End of alternation
$ # End of string
As a one-liner:
^(?:7(?:\.0)?|[1-6](?:\.[0-9])?|0?\.[1-9])$
In Java:
Pattern regex = Pattern.compile("^(?:7(?:\\.0)?|[1-6](?:\\.[0-9])?|0?\\.[1-9])$");
To complete the great #TimPietzcker answer,
this Regex...
^(?:7(?:\.0)?|[1-6](?:\.(?:[0-9])?)?|0?(?:\.(?:[1-9])?)?)$
also match:
0
0.
2.
.2
for anyone who needs it !

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" />