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))
Related
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})?)?)?)?$"
How do I match negative numbers as well by this regular expression? This regex works fine with positive values, but I want it to also allow negative values e.g. -10, -125.5 etc.
^[0-9]\d*(\.\d+)?$
Thanks
You should add an optional hyphen at the beginning by adding -? (? is a quantifier meaning one or zero occurrences):
^-?[0-9]\d*(\.\d+)?$
I verified it in Rubular with these values:
10.00
-10.00
and both matched as expected.
let r = new RegExp(/^-?[0-9]\d*(\.\d+)?$/);
//true
console.log(r.test('10'));
console.log(r.test('10.0'));
console.log(r.test('-10'));
console.log(r.test('-10.0'));
//false
console.log(r.test('--10'));
console.log(r.test('10-'));
console.log(r.test('1-0'));
console.log(r.test('10.-'));
console.log(r.test('10..0'));
console.log(r.test('10.0.1'));
Some Regular expression examples:
Positive Integers:
^\d+$
Negative Integers:
^-\d+$
Integer:
^-?\d+$
Positive Number:
^\d*\.?\d+$
Negative Number:
^-\d*\.?\d+$
Positive Number or Negative Number:
^-?\d*\.{0,1}\d+$
Phone number:
^\+?[\d\s]{3,}$
Phone with code:
^\+?[\d\s]+\(?[\d\s]{10,}$
Year 1900-2099:
^(19|20)[\d]{2,2}$
Date (dd mm yyyy, d/m/yyyy, etc.):
^([1-9]|0[1-9]|[12][0-9]|3[01])\D([1-9]|0[1-9]|1[012])\D(19[0-9][0-9]|20[0-9][0-9])$
IP v4:
^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]){3}$
I don't know why you need that first [0-9].
Try:
^-?\d*(\.\d+)?$
Update
If you want to be sure that you'll have a digit on the ones place, then use
^-?\d+(\.\d+)?$
Adding "-" minus followed by ? quantifier in front of [0-9] expression should do the work.
-?[0-9]
For reference
^b - ^ quantifier matches for any string begin with "b"
c? - ? quantifier matches for 0 or 1 occurrence of "c"
[0-9] - find any character between the [] brackets
\d - find a digit from 0-9
d* - * quantifier matches for zero or more occurrence of "d"
\. - matches a "." character
z+ - + quantifier matches for one or more occurrence of "z"
e$ - $ quantifier matches for any string end with "e"
Hope, it'll help to understand posted regex in the question.
UPDATED(13/08/2014): This is the best code for positive and negative numbers =)
(^-?0\.[0-9]*[1-9]+[0-9]*$)|(^-?[1-9]+[0-9]*((\.[0-9]*[1-9]+[0-9]*$)|(\.[0-9]+)))|(^-?[1-9]+[0-9]*$)|(^0$){1}
I tried with this numbers and works fine:
-1234454.3435
-98.99
-12.9
-12.34
-10.001
-3
-0.001
-000
-0.00
0
0.00
00000001.1
0.01
1201.0000001
1234454.3435
7638.98701
This will allow a - or + character only when followed by a number:
^([+-](?=\.?\d))?(\d+)?(\.\d+)?$
I have some experiments about regex in django url, which required from negative to positive numbers
^(?P<pid>(\-\d+|\d+))$
Let's we focused on this (\-\d+|\d+) part and ignoring others, this semicolon | means OR in regex, then the negative value will match with this \-\d+ part, and positive value into this \d+
This will allow both positive and negative integers
ValidationExpression="^-?[0-9]\d*(\d+)?$"
^[+-]?\d{1,18}(\.\d{1,2})?$
accepts positive or negative decimal values.
This worked for me, allowing both negative and positive numbers:
\-*\d+
If using C#:
Regex.Match(someString, #"\-*\d+").Value;
If you have this val="-12XXX.0abc23" and you want to extract only the decimal number, in this case this regex (^-?[0-9]\d*(\.\d+)?$) will not help you to achieve it. this is the proper code with the correct detection regex:
var val="-12XXX.0abc23";
val = val.replace(/^\.|[^-?\d\.]|\.(?=.*\.)|^0+(?=\d)/g, '');
console.log(val);
I had a case recently where students were entering only the accepted characters in a numeric response field, yet still managed to break things. Thus, I ended up using the following catch-all.
^[+-]?((\d*\.?\d+)|(\d+\.?\d*))$
This ensures everything that should work will work, including:
0
.0
0.0
-.11
+.2
-0.2
+01.
-123.
+123.4567890
-012.0
+1
-1.
The expression also rejects things that mischievous kids might enter which, while still being valid character input, would not be a valid number, such as:
+.
-
.
(nul or newline)
I found that the expression as most have it written here (ending with \d+$) will reject numbers if they include a decimal point without any numbers after it. And making that expression instead end with \d* would make the entire expression optional, thus causing it to match the entries in the second list above. But by using the capturing group with the boolean OR operator (|) to require at least one digit either after or before a decimal point, all bases are covered.
Just add a 0 or 1 token:
^-?[0-9]\d*(.\d+)?$
For negative number only, this is perfect.
^-\d*\.?\d+$
Regular expression for number, optional decimal point, optional negative:
^-?(\d*\.)?\d+$;
works for negative integer, decimal, negative with decimal
^(-?\d+\.)?-?\d+$
allow:
23425.23425
10.10
100
0
0.00
-100
-10.10
10.-10
-10.-10
-23425.23425
-23425.-23425
0.234
Simply /\d/ works as expected for all cases I can think of:
let ns = {
regex: {
num: /\d/
}
}
for (let i of [-2, -1, 0, 1, 2, 'one', 'negative one', Math.PI, Math.E, (42 * -1), (42 / -1), '-1', '0', '1', 1.01, -1.01, .1, -.1, Math.sqrt(42)]) {
console.log(ns.regex.num.test(i) + ': ' + i);
}
For more Math fun, check out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math
Hy, just a quick one here, does anyone know a good regular expression for a percentage and another number? I want to use it in a XML Schema..
Should Match:
-1
100.00
20.00
20.0
10.0
20
99.0
66.4
0.00
So it should match a percentage OR -1
My approach doesnt work...
([/-1]{1}|\d{1,3}\.\d{1,2})
Thanks!
(-1\n|\b(100|\d{1,2})(\n|(\.\d{1,2})))
Explanation:
(-1\n| // when not percentage OR ...
\b // word boundary - must not be other symbols in front
(100| // when integer part is equal to 100 OR ...
\d{1,2} // when integer part is number between 0 and 99
) // then after integer part must follow:
(\n| // new line symbol OR ...
(\.\d{1,2}) // dot symbol AND fractional part composed of 0 and 99
)
)
For regular expressions I usually use and suggest MDN as a reference.
That being said if I understand what you are trying to do this would work for you:
/(?=\s+|^)(?:-1|100(?:\.0+)?|\d{1,2}(?:\.\d{1,})?)(?=\s+)/gm
This would match strings that have nothing or white-spaces before and after
(?=\s+|^) content (?=\s+)
You can optionally alter that to ^(?: content)$ if you want each number to be the only thing on each line.
Where content is any of:
-1 ( -1 )
100 optionally folowed by "." and 1 or more 0s ( 100(?:\.0+)? )
1 or 2 digits optionally followed by "." and 1 or more decimals ( \d{1,2}(?:\.\d{1,})? )
You could alter the ending of {1,} to {1,X} where X is the max number of decimals you want to match.
For matching results check RegExr
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));