Regular Expression: Help Matching a number less than 24 - javascript

so I'm making this regular expression to verify some text boxes on a website that I'm designing for an internship.
The problem is that I'm not so keen on regular expressions, and I'm close to having a working one that matches a number between 0-24 and no more than two decimal places.
This is what I have so far. The pattern is also matching any string; such as, "a" or "az".
var pattern = "^([0-9]{0,2}?.?[0-9]{0,2}|1[0-9].?[0-9]{0,2}|2[0-4].?[0-9]{0,2})$";

To get a number between 0 and 24 (24 excluded) with optional up to two decimal places:
^(\d|1\d|2[0-3])(\.\d{1,2})?$
The decimal part:
\. - match the decimal dot
\d{1,2} - one or two digits
()? - makes it optional
The whole part:
\d - numbers 0-9
1\d - numbers 10-19
2[0-3] - numbers 20-23
(x|y|z) - one of x, y or z
As for the "why is my version matching things like "a" and "az" part" - it's a little complex, but it basically boils down to you using dots (like .?). In regex, a dot means "any one character". To make it match a literal dot, you need to escape it with a slash just like I did.
Minor remark: If you want optional leading zero for single digit numbers, replace 1\d with [01]\d. If you want mandatory leading zero for single digit numbers, replace \d|1\d with [01]\d. If you don't want leading zeroes, leave it as it is.

Assuming you do not want 05 or 5.50
^((?:[0-9]|1[0-9]|2[0-3])(?:\.(?:[1-9]|[0-9][1-9]))?)$
You can try it here

The following is a quick attempt to match a floating point number from 0 to 24.99 with up to two non-zero digits
^(([0-9])|([01][0-9])|(2[0-4]))(\.[0-9]{1,2})?$
I think it might be easier to use math to do this though...

You can see the explanation of the entire regex as well as test it out here. I have also added a few test cases.
^(\d|[01]\d|2[0-3])(\.\d{1,2})?$
Test cases:
Valid:
22
1.29
2.99
9.99
13.24
17.38
20.01
02.15
15.35
23.56
1.1
Invalid:
24.29
235.215
21.256

To get a integer number between 1 and 23: ^([1-9]|1[0-9]|2[0-3])$

Related

Why this regex fails when there is an extra zero?

I have created this regex to match dollar amounts more than $9,000.00.
\$(?=.{6,11}$)\d{1,3}(?:,\d{3})*
But it fails in cases like this,
$25,000.00. Text Goes here
$1,000,000.00
However it works in cases like this,
$25,000.0. T
$25,000.00
$999,000.00
How to fix this regex?
Some issues in your regex:
The look ahead assertion requires the that match can only start in the final 11 characters of the input string, since it has the $ anchor after at least 6 and at most 11 characters. So it is no surprise that "$25,000.00. Text Goes here" does not match. I suppose you don't want that $ anchor, and then the 11 is not useful anymore either.
The look ahead assertion requires that at least 6 characters follow after the currency symbol, however that could include non-digit characters, and so your regex will match the amount in `$300 oh" (6 characters follow after currency symbol).
There is no provision in your regex for decimals even though you say it works for examples that have decimals. But it will not include those decimals in the match. For instance, for input "$300,000.50" it will only match "$300,000" and not the 50 cents. You would need to accept an optional decimal point followed by one or two digits and then require there are no more decimal digits with a negative look-ahead.
The look-ahead assertion is not the right place to impose a maximum amount, because when you remove the $ (see first point) you must still require that there are no more digits after the 11th position. Instead, just remove the look-ahead assertion and match the patterns you want in more detail. There are just two options: either you have 2 or 3 digits followed by one digit group (for amounts between 10,000 and 999,999.99) or you have 1 to 3 digits followed by two digit groups (for amounts between 1,000,000 and 999,999,999.99). To avoid that more digits follow when no decimal part exists, use a negative look-ahead assertion: (?![,.]?\d).
All this is taken into account in this correction:
\$(?:\d{2,3}(?:,\d{3})|\d{1,3}(?:,\d{3}){2})((?![,.]?\d)|\.\d\d?(?!\d))
On regex101
To allow the same numbers without commas, add \d{5,9} as an option:
\$(?:\d{2,3}(?:,\d{3})|\d{1,3}(?:,\d{3}){2}|\d{5,9})(?:(?![,.]?\d)|\.\d\d?(?!\d))
On regex101
Totally new answer. After closer inspection I see that they have revised
the specifications on this question.
I am submitting this solution based on a $10,000.00 - $999,999,999.00 range
of unacceptable cash amounts. The comma's and decimal are optional.
There cannot be more than 3 consecutive decimal numbers after the period.
Ah, other specifications are dubious.
Note that a text representation of leading zero's is not allowed, which is a
distinction worth investigating as digits \d class is covers characters 0-9.
It is hard, if not impossible to match to infinity.
For example, the OP requested to match cash greater than $9,000 (Ah $10,000).
Regex has no representation of quantifiers representing infinity therefore
#Trincot tried to talk him into a max cash amount number to cap it.
In reality, you can only match the infinite with a negative of the finite.
So it is in the cosmos as it is in regex.
The only real way to match a number greater than another number is to
state that it is not in a finite range. In this case not in the range $0 - $9,999.
In this case they have established a range that the cash cannot be in.
That apparently is this $10,000.00 - $999,999,999.00 range, which
absolutely does not represent all values greater than $10,000.00
My original answer was to match $0 - $9,000 (original minimum) then post that regex in a negative assertion, thereby matching the infinite set of values
greater than $9,000 which was and is the only answer to matching cash values greater than
a fixed amount.
In the end, parsing values is only a preamble to getting it into a float
and there is no way to glean the final value ahead of that conversion.
Therefore, this is really an exercise in futility.
To that end :
$10,000.00 - $999,999,999.00
\$[1-9](?:\d{1,2}(?:,?\d{3}){1,2}|(?:,?\d{3}){2})(?:\.\d{0,2})?(?![,.]?\d)
https://regex101.com/r/1h4XW9/1
\$ [1-9]
(?:
\d{1,2}
(?: ,? \d{3} ){1,2}
| (?: ,? \d{3} ){2}
)
(?: \. \d{0,2} )?
(?! [,.]? \d )

Implemention of regex for float and int Bangla Numbers using js

I'm facing a problem.
I want to validate Bangla int and float numbers using RegEx.
I am using the following RegEx
([০-৯][০-৯]*$)
But it's not working on ২৬৭
And again, How I would implement floating bangla numbers (For example:৬৭.৫৬) supported regex once which will select int and float Bangla Numbers. Please somebody help me. (It's for my learning purposes only)
You may use the following to match simple integer or float Bengali numbers:
/[০-৯]+(?:\.[০-৯]+)?/
/[\u09E6-\u09EF]+(?:\.[\u09E6-\u09EF]+)?/
You may validate them (the whole string should match) with
/^[০-৯]+(?:\.[০-৯]+)?$/
/^[\u09E6-\u09EF]+(?:\.[\u09E6-\u09EF]+)?$/
See the regex demo.
Details:
^ - start of string
[\u09E6-\u09EF]+ - one or more Bengali digits
(?:\.[\u09E6-\u09EF]+)? - an optional occurrence of a . and one or more Bengali digits
$ - end of string.
Try this:
regex = /[০-৯]+(\.[০-৯]*)?$/
console.log(regex.test("২৬৭"))
Maybe that was a little bit confusing. Let's break the regex /[০-৯]+(\.[০-৯]*)?$/ down.
First part - `[০-৯]+`
This means that it will match 0-9, one or greater number of times.
Second part - `\.[০-৯]*`
This means that it will match a decimal point ., along with zero or greater numbers.
Third part - `(\.[০-৯]*)?`
The brackets just mean that you are grouping it. The question mark makes it optional.
Fourth part - `$`
Matches to the end of the string.
Putting that together and summarizing: First it matches for a string of numbers. After it encounters a non-number, it checks if it is a decimal point. If it is, then it matches the decimal, and however many numbers come after it (which might be none, meaning that the decimal is there for significant figure purposes, or for another reason).

Regex for non negative and non zero for the format ###.##

I have a requirement to validate some inputs which should be in format ###.##
Invalid inputs are:
-11.10 ==> no negative
000.00 or 0 ==> 0 not allowed should be positive
Valid inputs are:
1
11
111
1.1
11.11
111.11
I have tried with the following regex ^([^-]\d{0,2}(.\d{1,2})?)$ which fulfills my requirements except it's accepting 0 which I don't want. How I can modify my regex so only 0's do not get matched?
Thanks For Help
Try
^(?=.*[1-9])\d{1,3}(?:\.\d\d?)?$
It should do it for you.
It starts with a positive look-ahead to make sure there's a digit other than 0 present.
Then it matches 1-3 digits, optionally followed by a . and 1-2 digits.
Your regex101 updated.
([0-9]){1,3}(\.[0-9]{1,2})? is the expression you are searching for.
([0-9]){1,3} = any number sequence with a length from 1 up to 3
(\.[0-9]{1,2})? = "?" maybe there is a float tail
(\.[0-9]{1,2}) = float tail must start with a dot and decimal numbers have to be up to 2
There is a way to except all zero sequences but it will waste your time for no reason, as you can simply check it with if myNum > 0.
It will work for negative values also, but this regex excludes them too.
^[1-9][0-9]*(\.[0-9]+)?$|^0\.[0-9]+$
This will work for you. It accepts all valid positive decimal numbers excluding 0.

How to write a regular expression to validate a 4 character string as a non-zero binary number?

I have a string E.g 1001, which needs to be exactly 4 chars and can be any combination of 0 and 1, but not all zeros (all ones is ok).
I thought of:
^[01]{4}$
won't work because it accepts 0000
I will be using PHP or JavaScript to do this.
Just adding a detail.
I will be using this to validate the answers for a multi choise questionnaire before they go in the database therefore the string will have length N depending on the number of choices for the question.
so a function to provide the general solution would be great.
It should work
^(?!0000)[01]{4}$
DEMO
Note: Use gm as modifier
Read more about Lookahead and Lookbehind Zero-Length Assertions that actually matches characters, but then gives up the match, returning only the result: match or no match.
Pattern explanation:
^ the beginning of the string
(?! look ahead to see if there is not:
0000 '0000'
) end of look-ahead
[01]{4} any character of: '0', '1' (4 times)
$ end of the string
Another simple solution is this:
^[01]{4}(?<=100|10|1)$
Based on your two possible values [0,1] you only have 8 distinct possibilities:
0000
0001
0010
0011
0100
0101
0110
0111
1111
Your original Regex would hit on all these values. However, the positive look-behind code ensures that the code will either end in '1, '10' or '100'. This covers all possible values except 0000.
The regex:
^(1[01]{3}|01[01]{2}|001[01]|0001)$
Will work and does not rely on look-ahead or look-behind operations which are not, necessarily, available in all regex implementations. Although, now that the question has been edited to provide the languages which will be used: Both PHP and JavaScript regular expressions have negated look-ahead. In those languages, the regex ^(?!0000)[01]{4}$ will work.
The regex at the top of this answer uses multiple terms to build up successively more explicit matches as each character position is specified. The point is that there must be at least one 1 character in the matching four character string. Once a 1 character is encountered in the string, we do not care what the remaining characters are, other than being [01].
The first term 1[01]{3} will match any four 0 and 1 digits that start with 1. This covers all desired matching strings where the first digit is a 1 leaving only desired strings starting with 0 not yet defined as matching.
The second term 01[01]{2} will match any four 0 and 1 digits that start with 01. This leaves only desired strings which start with 00 not yet defined as matching.
The third term 001[01]{2} will match 0010 and 0011
The fourth term 0001 matches the one desired string not matched by the other terms.
Validate an N character long non-zero binary string:
Use a regex comparison and a length check:
Your comments indicate that you have much longer (e.g. 40 characters) similar strings which you need to match in other circumstances.
Given that you have the need to check various different length strings, you are probably best off creating a single function which is able to test multiple different lengths.
In JavaScript, a possibility would be:
function isNonZeroBinaryStringOfLengthN(str, len) {
//True if string is all 0 or 1 with at least one 1 and is the right length.
return (str.length == len && /^[01]*1[01]*$/.test(str) );
}
It is not a good idea to only use the built in functions to parse the string to an integer:
For this circumstance, you are probably best off sticking with a regex based solution rather than using either the PHP intval($str,2) or JavaScript parseInt(str,2). The reason for this is that neither function properly validates the string.
In PHP the command:
echo intval('011134011',2);
prints
7
In JavaScript the command:
console.log(parseInt("0101382730101",2));
prints:
5
This means that if you use one of the internal string->int parsing functions, you still have to separately validate the string you are passing to either function to match ^[01]{n}$. Given that you must to that anyway, you are probably better off using the single regex and length test mentioned above without parsing the string to an int.

Regex for number with decimals and thousand separator

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).

Categories