I would like to use regex to match a string of exactly 2 characters, and both of those characters have to be between 0 and 9.
Example: if I provide 12 - True and if I provide 123- it should give false.
I have tried below examples.
\d{6}$
^[0-9]{2}$
However, Even I enter 123, it is giving as true but I need it as false as I need exactly two.
try this regex
^\d\d$
test here https://www.regextester.com/1966
Using ^[0-9]{2}$ you get a number between 0 and 9 and then two digits.
If you only want two digits can use \d{2}
I think the best way is to use wc -l to count the amount of charecters.
i.e:
NUM=123
if [[ `echo ${NUM} | wc -l` -gt 2 ]];then
echo "You provided a number grater than 2 digits"
exit 1
fi
Related
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.
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])$
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.
I have a list of phone numbers which are formatted in multiple ways such as: (212)-555-1234 or 212-555-1234 or 2125551234.
Using JavaScript, what would be the best way to extract only the area code out of these strings?
First, remove everything that is not a digit to get the plain number. Then, get the first three digits via slicing:
return myString.replace(/\D/g,'').substr(0, 3);
Get the first 3 consecutive digits...
/[0-9]{3}/.exec("(212)-555-1234")[0]
Sample (fiddle):
console.log(/[0-9]{3}/.exec("(212)-555-1234")[0]); // 212
console.log(/[0-9]{3}/.exec("212-555-1234")[0]); // 212
console.log(/[0-9]{3}/.exec("2125551234")[0]); // 212
Take the first 3 digits of a 10 digit number, or the first 3 digits after the 1 of an 11 digit number starting with 1. This assumes your domain is U.S. phone numbers.
You can also use my library.
https://github.com/Gilshallem/phoneparser
Example
parsePhone("12025550104");
result: { countryCode:1, areaCode:202, number:5550104, countryISOCode:"US" }
Regex as '^\(*(\d{3})' should do it. Get the first group from the match.
Here ^ will start the match from beginning, \d{3} will match 3 digits. \(* will match the optional starting parenthesis. You don't need to care about next digit or symbols after the area code.
I want the strict regular expression for 0:59 to 99:59 Hours. It should allow 0 to 99 Hours.
How could it be done.
/^([0-9]{1,2}(\:[0-5][0-9])?)$/
is working properly
Even something as simple as \d{1,2}(:[0-5]\d)? should suffice.
\d A digit
\d{1,2} One or two digits
\d{1,2}: One or two digits followed by :
\d{1,2}:[0-5] One or two digits followed by : followed by a digit 0 to 5
\d{1,2}:[0-5]\d ...followed by a digit (0 to 5) and another digit
\d{1,2}(:[0-5]\d)? ...making the :XX part optional due to the ?
Second update: Fixed to account for the optional :XX part.
Try it this way
/\d{1,2}(:[0-5]\d)?/
This regex will also validate numbers from 0 to 99 with or without : and post data. :)
UPDATE
javascript code for the same would be like
var field1 = "0:00"
var regTime = /\d{1,2}(:[0-5]\d)?/ ;
if(field1 == field1.match(regTime)[0]){ alert('matches') }