RegEx complex pattern - javascript

I have to write regex that checks if string:
length is 5-15 characters long
has at least 2 uppercase letters
has at least 2 lowercase letters
and has 1 digit
I appreciate any help because I am really stuck on this and don't have any ideas how to solve this.

You can use look ahead to check all conditions, and then match 5 to 15 characters (any), making sure there is nothing else (^ and $):
^(?=(?:.*[A-Z]){2})(?=(?:.*[a-z]){2})(?=.*\d).{5,15}$
^: start of string
(?= ): positive look ahead. Does not grab any characters, but just looks ahead to see if the pattern would be matched
(?: ): make this group non-capturing, i.e. you'll not get it as capturing group that you can reference with $1 or \1 (language dependent)
.*[A-Z]: 0 or more character(s) followed by a capital letter
.*[a-z]: 0 or more character(s) followed by a lower case letter
.*\d: 0 or more character(s) followed by a digit
{2}: previous pattern must match twice
.{5-15}: 5 to 15 characters.
$: end of string
In JavaScript you can test a string against a regular expression with test, for example:
var regex = /^(?=(?:.*[A-Z]){2})(?=(?:.*[a-z]){2})(?=.*\d).{5,15}$/;
console.log(regex.test('a9B1c')); // false, missing capital letter
console.log(regex.test('a9B1cD')); // true

trinctot was right first, but depending on who is using your code and for what, this might be easier to maintain/modify:
var lowerPass = 2 <= (string.match(/[a-z]/g) || []).length;
var upperPass = 2 <= (string.match(/[A-Z]/g) || []).length;
var digitPass = 1 <= (string.match(/[0-9]/g) || []).length;
var lengthPass = 5 <= string.length <= 15;
var stringPass = lowerPass + upperPass + digitPass + lengthPass == 4;

Try this
^([a-z]{2,}[A-Z]{2, }[0-9]{1}+) {5, 15}$

Related

Regex to check for 3 same letters in a string?

I need to create regex which will look for 3 same letters in a string, regardless of the order.
Example:
'aa2ff333' -> false
'aa2a' -> true
'aaa2' -> true
I tried this but it check for consecutive letters:
(.)\1\1
Any advice?
You may use this regex with lookahead:
/([a-zA-Z])(?=(?:.*?\1){2})/
RegEx Demo
RegEx Details:
([a-zA-Z]): Match a letter [a-zA-Z] and capture it in group #1
(?=: Start lookahead
(?:.*?\1){2}: That has at least 2 occurrences of same character as in capture group #1. .*?\1 Matches back-reference \1 after 0 or more of any character. This allows matching repetitions anywhere in input.
): End lookahead
One way is to loop through the string and count occurrence of each character then check if any of character appears for exact three times
let threeChars = (str) => {
let obj = [...str].reduce((op, inp) => {
if (/[a-z]/i.test(inp)) {
op[inp] = op[inp] || 0
op[inp] += 1
}
return op
}, {})
return Object.values(obj).some(v => v === 3)
}
console.log(threeChars('aa2ff333'))
console.log(threeChars('aa2a'))
console.log(threeChars('aaa2'))
P.S:-
You can make it case insensitive by removing the i flag
In case you need to at least 3 character you can change v == 3 to v >= 3

Regex for getting only the last N numbers in javascript

I've being trying to generate a regex for this string:
case1: test-123456789 should get 56789
case2: test-1234-123456789 should get 56789
case3: test-12345 should fail or not giving anything
what I need is a way to get only the last 5 numbers from only 9 numbers
so far I did this:
case.match(/\d{5}$/)
it works for the first 2 cases but not for the last one
You may use
/\b\d{4}(\d{5})$/
See the regex demo. Get Group 1 value.
Details
\b - word boundary (to make sure the digit chunks are 9 digit long) - if your digit chunks at the end of the string can contain more, remove \b
\d{4} - four digits
(\d{5}) - Group 1: five digits
$ - end of string.
JS demo:
var strs = ['test-123456789','test-1234-123456789','test-12345'];
var rx = /\b\d{4}(\d{5})$/;
for (var s of strs) {
var m = s.match(rx);
if (m) {
console.log(s, "=>", m[1]);
} else {
console.log("Fail for ", s);
}
}
You can try this:
var test="test-123456789";
console.log((test.match(/[^\d]\d{4}(\d{5})$/)||{1: null/*default value if not found*/})[1]);
This way supports default value for when not found any matching (look at inserted comment inline above code.).
You can use a positive lookbehind (?<= ) to assert that your group of 5 digits is preceeded by a group of 4 digits without including them in the result.
/(?<=\d{4})\d{5}$/
var inputs = [
"test-123456789", // 56789
"test-1234-123456789", // 56789
"test-12345", //fail or not giving anything
]
var rgx = /(?<=\d{4})\d{5}$/
inputs.forEach(str => {
console.log(rgx.exec(str))
})

JS Regex for a string contains fixed number of letters

Let's say I need to have minimum 5 letters in a string not requiring that they are subsequent. The regex below checks subsequent letters
[A-Za-z]{5,}
So, "aaaaa" -- true, but "aaa1aa" -- false.
What is the regex to leave the sequence condition, that both of the strings above would pass as true.
You could remove all non-letter chars with .replace(/[^A-Za-z]+/g, '') and then run the regex:
var strs = ["aaaaa", "aaa1aa"];
var val_rx = /[a-zA-Z]{5,}/;
for (var s of strs) {
console.log( val_rx.test(s.replace(/[^A-Za-z]+/g, '')) );
}
Else, you may also use a one step solution like
var strs = ["aaaaa", "aaa1aa"];
var val_rx = /(?:[^a-zA-Z]*[a-zA-Z]){5,}/;
for (var s of strs) {
console.log( s, "=>", val_rx.test(s) );
}
See this second regex demo online. (?:[^a-zA-Z]*[a-zA-Z]){5,} matches 5 or more consecutive occurrences of 0 or more non-letter chars ([^a-zA-Z]*) followed with a letter char.
Allow non-letter characters between the letters:
(?:[A-Za-z][^A-Za-z]*){5,}
If you have to use a regular expression only, here's one somewhat ugly option:
const check = str => /^(.*[A-Za-z].*){5}/.test(str);
console.log(check("aaaaa"));
console.log(check("aa1aaa"));
console.log(check("aa1aa"));
w means alphanumeric in regex,
it will be ok : \w{5,}
[a-zA-Z0-9]{5,}
Just like this? Or do you mean it needs to be a regex that ignores digits? Because the above would match aaaa1 as well.

regex validation from a to z with an exception of certain characters

I have a variable like this
var time = "12h 55m";
I am only allowed to use H,h,M,m characters in the string. If i have something like this
var time = "12hk 55m";
then it should produce an error. how can I validate this using regex expression.'
looking for something like this
if (stringToTest.match(/^[a-zA-Z0-9]*$/))
Try
/^\d{1,2}[hm]\s+\d{1,2}[hm]$/i
It matches 2 digits followed by either h or m, followed by one or more space, followed by 2 digits followed by either h or m
Following will match
"12h 55m".match(/^\d{1,2}[hm]\s+\d{1,2}[hm]$/i)
"12m 55h".match(/^\d{1,2}[hm]\s+\d{1,2}[hm]$/i)
"2m 55h".match(/^\d{1,2}[hm]\s+\d{1,2}[hm]$/i)
"12m 5h".match(/^\d{1,2}[hm]\s+\d{1,2}[hm]$/i)
These will not
"122h 555m".match(/^\d{1,2}[hm]\s+\d{1,2}[hm]$/i)
The reg in regex stands for regular and your data seems to have a possibility to be irregular. I'd recommend to do the check differently but since you're looking for a regex solution:
/^(\d{2,3}h\s+\d{1,2}m)|(\d{1,2}m\s+\d{2,3}h)$/gi
This will match h and m in either order but will reject if either is in the string twice.
You could use following regex ^\d{1,2}[hmHM]\s\d{1,2}[hmHM]:
^ asserts position at start of the string
\d matches a digit (equal to [0-9])
{1,2} Quantifier — Matches between 1 and 2 times, as many times as possible, giving back as needed
[hmHM] matches a single character in the list hmHM (case sensitive)
\s matches any whitespace character
\d{1,2}[hmHM] as described above
\g modifier: global. All matches (don't return after first match)
See following snippet to test it:
var regex = /^\d{1,2}[hmHM]\s\d{1,2}[hmHM]/g;
function check(par){
console.log(par.value + " match: " + regex.test(par.value));
}
Insert a text in the input <input type="text" id="test" value="" onchange="javascript:check(this)">
The accepted answer apparently satisfies the OP. But I noticed that in this comment the OP says that the character symbols should not be repeated. For example, 12h 12h should be invalid but all answers match this. I don't think this can be done using only regex. So here is an alternative solution:
function timeParser(timeStr) {
var acChars = ['h', 'H', 'm', 'M'];
if ((timeStr.match(/\s/g) || []).length !== 1) return false;
var tokens = timeStr.split(' ');
for (var token of tokens) {
var rx = new RegExp("\\d{1,3}[" + acChars.join("") + "]", "g");
if (!token.match(rx) ||
token.match(rx).length !== 1 ||
token !== token.match(rx)[0]) return false;
var tc = token.charAt(token.length - 1);
acChars.splice(acChars.indexOf(tc), 1);
}
return true;
}
var timearr = ["12h 12h", "1m1h 515M", "12hk 55m", "H 12m", "m 12H", "12H 11m", "00m 001h", "20M 1"];
for (var tim of timearr)
console.log(timeParser(tim));
and 12h 12h is not matched.

Regular expression for any number of characters unlimited but should allow only 12 numbers

I am facing difficulty in regular expression.
The requirement is a regular expression for any number of characters unlimited, but should allow only 12 numbers {digits}.
Please help, Thanks.
Why not something like this:
var s = '12345aaaaaaaaaaaaaaaaabc444';
var maxDigits = 12,
len = s.length,
numDigits = 0,
newLen;
if (len > maxDigits) {
newLen = s.replace(/[0-9]/g, '').length;
numDigits = len - newLen;
}
if (numDigits > maxDigits) {
//error
}
I would think this regex would do the trick:
/^(.*?[\d].*?){12}$/
You are doing an ungreedy match for any number of characters on either side of a digit. That subpattern must be present 12 times.
[0-9]{12}
Try this... This will provide you 12 digits. 12 and only 12.
now you need to add any char but not numbers, need help?
Example for matching 3 digits in a string:
/^(([^\d]*\d[^\d]*){3})$/.test('asd1a2a4a') // -> (3 digits) true
/^(([^\d]*\d[^\d]*){3})$/.test('asd1a2a44a') // -> (4digits) false

Categories

Resources