Regex Regular Expression for Number Range Check between -2 and 5 - regex

I've got the following regular expression shown below which checks the range between 0 and 5.
^(([0-4])+(.\d)?)|((5)+(.0)?)$
I will need to change it so it checks the range between -2 to 5 instead but am not familiar with this code.
Can I get someone to make a quick change so the expression will then check between -2 and 5 please.
Thank you very much!

I understand that we are to match integers and floats with one decimal digit that fall between -2 and 5.
You can use the following regular expression with virtually all languages.
r = /\A(?:-2(?:\.0)?|-1(?:\.\d)?|-0\.[1-9]|[0-4](?:\.\d)?|5(?:\.0)?)\z/
Here I test it with Ruby.
'-2'.match? r #=> true
'-2.0'.match? r #=> true
'-1.8'.match? r #=> true
'-1.0'.match? r #=> true
'-1'.match? r #=> true
'-0.3'.match? r #=> true
'0'.match? r #=> true
'0.0'.match? r #=> true
'0.3'.match? r #=> true
'3'.match? r #=> true
'3.3'.match? r #=> true
'5'.match? r #=> true
'5.0'.match? r #=> true
'-2.1'.match? r #=> false
'-1.85'.match? r #=> false
'-0'.match? r #=> false
'-0.0'.match? r #=> false
'0.34'.match? r #=> false
'5.1'.match? r #=> false

This should work for all numbers from -2.0 to 5.0 inclusive which have 0 or 1 digit after the decimal place:
^((-[0-1]|[0-4])(\.\d)?|(-2|5)(\.0)?)$
Test cases: https://regex101.com/r/bInayE/2/
If you want to allow any number of digits after the decimal place (ex. 2.157):
^((-[0-1]|[0-4])(\.\d+)?|(-2|5)(\.0+)?)$
Test cases: https://regex101.com/r/zp01M6/3/
In case you want to be able to update these in the future:
[0-1] refers to the range of digits which can be preceded by a minus sign and have digits after a decimal point
[0-4] is the range of digits which can have digits after a decimal point without being preceded by a minus sign
(-2|5) are the numbers which can only be followed by .0
Update:
Shortened both expressions by combining the -2 and 5 cases as suggested by #Robert McKee.
Added case for negative numbers starting with 0 as pointed out by #Cary Swoveland

Regex are an awkward way to check for ranges, so I would suggest you try validating ranges in a more traditional way. I remember doing something similar
to validate ip addresses, and it got a lot more complicated than I expected.
With that said, that regex you pasted doesn't actually check for a 0-5 range. In fact, you could get any char in there, after a "5" and before a "0" (something like 5f0 for instance).
With a regex like the one below, you could validate the input in this set {-2,-1,0,1,2,3,4,5}. You may add the ^ at the beginning and $ at the end, so the regex matches the whole line.
(-[1-2]|[0-5])

Related

How do I fix this regex to match the strings I want?

I need to find out specific user names that meet a certain - albeit rather wide - criteria. My knowledge at regex is very limited so while my regex constructs did match what I wanted, they also matched about everything else. Can you help me?
The requirements for a valid match are:
string length: exactly 7 characters
contains only alphanumeric characters, mixed upper and lower case, or numbers 0-9
contains at least one number 0-9, can be more than that but never 3 in a row
not all upper case (can be all lower case but never upper case)
Unfortunately, the numbers can be anywhere in the string, and the alphanumeric characters can also be any combination.
Here is an excerpt of the data I need to match:
cgxh21o *
crittaz
Mist246
nOnameR
Gorebag
pu50pce *
rmygy62 *
aeifnz0 *
orp5k1v *
okn5nvr *
The ones marked with * are the ones I want to match. The remaining ones are valid and must not be included.
Is this even possible using regex?
My last attempt was:
/[a-z{0,}A-Z{0,}0-9{1,}]{7}+
but then I found user names that didn't follow that notation at all (more than one number) so it didn't work.
Here's a relatively short and simple regex that will work:
(?=(^.{7}$))(?=.*[a-z])(?=.*\d)(?!.*\d{3})
regex101 demo
Explanation:
(?=(^.{7}$)) check that there's exactly 7 characters (and capture them)
(?=.*[a-z]) at least one lower case letter
(?=.*\d) at least one digit
(?!.*\d{3}) there isn't 3 digits in a row anywhere
Here's a Python demo:
import re
pattern = re.compile(r"(?=(^.{7}$))(?=.*[a-z])(?=.*\d)(?!.*\d{3})")
ls = ["cgxh21o", "crittaz", "Mist246", "nOnameR", "Gorebag",
"pu50pce", "rmygy62", "aeifnz0", "orp5k1v", "okn5nvr",
"OKN5NVR", "short1", "aeifnz0aaaaaa", "12CeE12"]
for elem in ls:
print(elem, bool(re.search(pattern, elem)))
Output:
cgxh21o True
crittaz False
Mist246 False
nOnameR False
Gorebag False
pu50pce True
rmygy62 True
aeifnz0 True
orp5k1v True
okn5nvr True
OKN5NVR False
short1 False
aeifnz0aaaaaa False
12CeE12 True
You could use lookahead assertions:
^(?=[^a-z\s]*[a-z])(?=[^\d\s]*\d)(?!.*\d{3})[a-zA-Z0-9]{7}$
Explanation
^ Start of string
(?=[^a-z\s]*[a-z]) Assert a lowercase char a-z
(?=[^\d\s]*\d) Assert a digit
(?!.*\d{3}) Assert not 3 digits in a row
[a-zA-Z0-9]{7} Match 7 times any of the listed
$ End of string
Regex demo
Here's a possibility based on your updated question:
^(?![a-zA-Z]{7}|.*[0-9]{3}.*|[A-Z0-9]{7})([a-zA-Z0-9]){7}$
Doesn't match
crittaz
nOnameR
Gorebag
ABCDEFG
aBCDEFG
1234567
Mist246
ABCDEF7
Matches
cgxh21o
pu50pce
rmygy62
aeifnz0
orp5k1v
okn5nvr
There's probably a number of ways to do this. This one looks for 7 alphanumeric, but not if there's only 7 alphabetic, not if there's only uppercase and numbers, and not if there's 3 digits in a row...

Regex for double only input in textfield [duplicate]

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

Regex expression of Positiove,Negative decimal numbers

Im trying to figure out regular expression for negative and positive decimal numbers.
for example -
-11 = true
11 = true
-11.11 = true
11.11 = true
I thought about
(-)?([0-9])+(.)?([0-9])*|0
but it doesn't work well.
Any ideas ? Thanks.
try -?[0-9]*(\.[0-9]*)?. Make sure you escape that period character!
https://regex101.com/r/FFPEUA/1
-?([0-9]*(\.[0-9]*)?|\.[0-9]+)
This is an or-regex. The left side catches any integer and decimal constructed by integer followed by . followed by more digits. The right side catches numbers written as . followed by digits.

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 !

Regexes for integer constants and for binary numbers

I have tried 2 questions, could you tell me whether I am right or not?
Regular expression of nonnegative integer constants in C, where numbers beginning with 0 are octal constants and other numbers are decimal constants.
I tried 0([1-7][0-7]*)?|[1-9][0-9]*, is it right? And what string could I match? Do you think 034567 will match and 000083 match?
What is a regular expression for binary numbers x such that hx + ix = jx?
I tried (0|1){32}|1|(10)).. do you think a string like 10 will match and 11 won’t match?
Please tell me whether I am right or not.
You can always use http://www.spaweditor.com/scripts/regex/ for a quick test on whether a particular regex works as you intend it to. This along with google can help you nail the regex you want.
0([1-7][0-7])?|[1-9][0-9] is wrong because there's no repetition - it will only match 1 or 2-character strings. What you need is something like 0[0-7]*|[1-9][0-9]*, though that doesn't take hexadecimal into account (as per spec).
This one is not clear. Could you rephrase that or give some more examples?
Your regex for integer constants will not match base-10 numbers longer than two digits and octal numbers longer than three digits (2 if you don't count the leading zero). Since this is a homework, I leave it up to you to figure out what's wrong with it.
Hint: Google for "regular expression repetition quantifiers".
Question 1:
Octal numbers:
A string that start with a [0] , then can be followed by any digit 1, 2, .. 7 [1-7](assuming no leading zeroes) but can also contain zeroes after the first actual digit, so [0-7]* (* is for repetition, zero or more times).
So we get the following RegEx for this part: 0 [1-7][0-7]*
Decimal numbers:
Decimal numbers must not have a leading zero, hence start with all digits from 1 to 9 [1-9], but zeroes are allowed in all other positions as well hence we need to concatenate [0-9]*
So we get the following RegEx for this part: [1-9][0-9]*
Since we have two options (octal and decimal numbers) and either one is possible we can use the Alternation property '|' :
L = 0[1-7][0-7]* | [1-9][0-9]*
Question 2:
Quickly looking at Fermat's Last Theorem:
In number theory, Fermat's Last Theorem (sometimes called Fermat's conjecture, especially in older texts) states that no three positive integers a, b, and c can satisfy the equation an + bn = cn for any integer value of n greater than two.
(http://en.wikipedia.org/wiki/Fermat%27s_Last_Theorem)
Hence the following sets where n<=2 satisfy the equation: {0,1,2}base10 = {0,1,10}base2
If any of those elements satisfy the equation, we use the Alternation | (or)
So the regular expression can be: L = 0 | 1 | 10 but can also be L = 00 | 01 | 10 or even be L = 0 | 1 | 10 | 00 | 01
Or can be generalized into:
{0} we can have infinite number of zeroes: 0*
{1} we can have infinite number of zeroes followed by a 1: 0*1
{10} we can have infinite number of zeroes followed by 10: 0*10
So L = 0* | 0*1 | 0*10
max answered the first question.
the second appears to be the unsolvable diophantine equation of fermat's last theorem. if h,i,j are non-zero integers, x can only be 1 or 2, so you're looking for
^0*10?$
does that help?
There are several tool available to test regular expressions, such as The Regulator.
If you search for "regular expression test" you will find numerous links to online testers.