RegEx for validating three alphanumeric conditions - javascript

I have the current regex that works fine:
^[a-zA-Z]{2}[0-9]{8}$
It works for existing pattern containing exactly 2 letters followed by exacly 8 digits, such as AB12345678 or yZ01928374
I need to change it to a new regex that satisfies 3 conditions:
1) if the first 2 letters are followed by a single digit "9", then it can be followed by 7 or 8 digits [0-9]{7,8}. Eg AB91234567 or AC912345678 are both valid.
2) if the first 2 letters are followed by a single digit between 0-5, then it can be followed by exactly 8 digits [0-9]{8}. Eg AB412345678
3) if the first 2 letters are followed by digit between 6-8, then it can be followed by exactly 7 digits [0-9]{7}. Eg AB71234567
I've got bits and pieces but I'm really not sure how to put all 3 conditions together in 1 nice expression.

You can use alternation and add the desired rules for values followed by after first two alphabets
let test = ['AB91234567','AB412345678','AB912','ABC123']
test.forEach( value => {
console.log(/^[a-zA-Z]{2}(?:9\d{7,8}|[0-5]\d{8}|[6-8]\d{7})$/.test(value))
})

You can use alternations to define different conditions and use this regex,
^[a-zA-Z]{2}(?:9[0-9]{7,8}|[0-5][0-9]{8}|[6-8][0-9]{7})$
Explanation:
^ - Start of string
[a-zA-Z]{2} - Matches two alphabets
(?: - Start of non-grouping pattern
9[0-9]{7,8} - If the next digit is 9 then it can be followed by 7 to 8 digits
| - Alternation
[0-5][0-9]{8} - If the next digit is zero to five then it can only have eight digits
| - Alternation
[6-8][0-9]{7}) - If the next digit is six to eight then it can only have seven digits and end of non-group pattern
$ - End of string
Regex Demo
JS Code demo,
const arr = ['ab91234567','ab912345678','ab9123456789','sd012345678','sd0123456789','df71234567','df712345678']
arr.forEach(x => console.log(x + " --> " + /^[a-zA-Z]{2}(?:9[0-9]{7,8}|[0-5][0-9]{8}|[6-8][0-9]{7})$/.test(x)))

Related

Regexp to allow letters, numbers and -

I have a problem with creating regexp to allow:
exactly 2 letters at the beginning
exactly 10 numbers after letters
at most 4 "-" between numbers (should allow also without it)
so example of valid string is GB123-55-22-22-6,
my current regexp is: /^([A-Z]{2})?[0-9]{10}$/. He allow GB1235522226 but I have a problem with "-".
can somoene tell me how to allow this regexp to use at most 4 "-" chars?
thanks for any help!
You can use
^(?:[A-Z]{2})?(?=(?:-?\d){10}$)[0-9]+(?:-[0-9]+){0,4}$
See the regex demo.
Details:
^ - start of string
(?:[A-Z]{2})? - optional two letters
(?=(?:-?\d){10}$) - there must be 10 digits optionally separated with a - till end of string, the string must end with a digit
[0-9]+ - one or more digits
(?:-[0-9]+){0,4} - zero to four occurrences of a hyphen and then one or more digits
$ - end of string.

Regex validation for mixed digits for a max of 6 characters

I need a regex validation for mixed length, a total length of 6 characters in that 4-6 characters in caps/numbers and 0-2 spaces.
I tried like
^[A-Z0-9]{4,6}+[\s]{0,2}$
but it results in a max length of 8 characters, but I need a max of 6 characters.
If the alphanumeric chars should only appear at the start of the string and the whitespaces can appear at the end (i.e. the order of the alphanumerics and whitespaces matters), you may use
/^(?=.{6}$)[A-Z0-9]{4,6}\s*$/
See the regex demo
Details
^ - start of string
(?=.{6}$) - the string length is restricted to exactly 6 non-line break chars
[A-Z0-9]{4,6} - 4, 5 or 6 uppercase ASCII letters or digits
\s* - 0+ whitespaces (but actually, only 0, 1 or 2 will be possible to add as the total length is already validated with the lookahead)
$ - end of string.
If you want to match the alphanumeric and whitespaces anywhere inside the string, you need a lookaround based regex like
^(?=(?:[^A-Z0-9]*[A-Z0-9]){4,6}[^A-Z0-9]*$)(?=(?:\S*\s){0,2}\S*$)[A-Z0-9\s]{6}$
See the regex demo
Details
^ - start of string
(?=(?:[^A-Z0-9]*[A-Z0-9]){4,6}[^A-Z0-9]*$) - a positive lookahead that requires the presence of 4 to 6 letters or digits anywhere inside the string
(?=(?:\S*\s){0,2}\S*$) - a positive lookahead that requires the presence of 0 to 2 whitespaces anywhere inside the string
[A-Z0-9\s]{6} - 6 ASCII uppercase letters, digits or whitespaces
$ - end of string.
To shorten the pattern, the second lookahead can be written as (?!(?:\S*\s){3}), it will fail the match if there are 3 whitespace chars anywhere inside the string. See the regex demo.
You can use | characters to accommodate several cases into one.
const regex = /(^[A-Z0-9]{4}\s{2}$)|(^[A-Z0-9]{5}\s$)|(^[A-Z0-9]{6}$)/g;
alert(regex.test(prompt('Enter input, including space(s)')));
If you want to match zero, one or two spaces at the end, you could use an alternation for those 3 cases.
^(?:[A-Z0-9]{4}[ ]{2}|[A-Z0-9]{5}[ ]|[A-Z0-9]{6})$
Regex demo
Explanation
^ Assert the start of the string
(?: Non capturing group
[A-Z0-9]{4}[ ]{2} Match uppercase or digit 4 times followed by 2 spaces
| Or
[A-Z0-9]{5} Match uppercase or digit 5 times followed by 1 space
| Or
[A-Z0-9]{6} Match uppercase or digit 6 times
) Close non capturing group
$ Assert the end of the string

RegEx expression in phone number format (no more than 10 digits) that does not accept 0 or 1 as first number

I would like a reg ex expression that is in phone number format (XXX)XXX-XXXX
..that can be no more than 10 digits, and does not accept 0 or 1 as the first number.
Right now I have -
/^(?!\(?[0-9]11\)?|\(?1[0-9][0-9]\)?|\(?0[0-9][0-9]?)(\(?\d{3}\)?\s?)(\(?\d{3})(\s?-?\s?)(\d{4})$/;
But it does not work.
Any help with this would be greatly appreciated.
You can use expression:
^\([2-9][0-9]{2}\)[0-9]{3}-[0-9]{4}$
^ Assert position beginning of line.
\( An opening bracket (.
[2-9] First digit between 2 and 9.
[0-9]{2} Two digits.
\) A closing bracket ).
[0-9]{3} Three digits.
- A hyphen character.
[0-9]{4} Four digits.
$ Assert position end of line.
You can test it here.
We'll match 3 numbers not starting with 0 or 1 surrounded by parenthesis with \([2-9]\d{2}\) then 3 numbers alone with \d{3} then 4 numbers following a dash with -\d{4}.
Your full expression is /\([2-9]\d{2}\)\d{3}-\d{4}/
const regex = /\([2-9]\d{2}\)\d{3}-\d{4}/;
const valid = '(211)222-3333';
const invalid = '(111)222-3333';
console.log(regex.test(valid));
console.log(regex.test(invalid));

Is there a difference between \d and \d+? [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 6 years ago.
https://www.freecodecamp.com/challenges/find-numbers-with-regular-expressions
I was doing a lesson in FCC, and they mentioned that the digit selector \d finds one digit and adding a + (\d+) in front of the selector allows it to search for more than one digit.
I experimented with it a bit, and noticed that its the g right after the expression that searches for every number, not the +. I tried using \d+ without the g after the expression, and it only matched the first number in the string.
Basically, whether I use \d or \d+, as long as I have the g after the expression, It will find all of the numbers. So my question is, what is the difference between the two?
// Setup
var testString = "There are 3 cats but 4 dogs.";
var expression = /\d+/g;
var digitCount = testString.match(expression).length;
The g at the end means global, ie. that you want to search for all occurrences. Without it, you'll just get the first match.
\d, as you know, means a single digit. You can add quantifiers to specify whether you want to match all the following, or a certain amount of digits afterwards.
\d means a single digit
\d+ means all sequential digits
So let's say we have a string like this:
123 456
7890123
/\d/g will match [1,2,3,4,5,6,7,8,9,0,1,2,3]
/\d/ will match 1
/\d+/ will match 123
/\d+/g will match [123,456,7890123]
You could also use /\d{1,3}/g to say you want to match all occurrences where there are from 1 to 3 digits in a sequence.
Another common quantifier is the star symbol, which means 0 or more. For example /1\d*/g would match all sequences of digits that start with 1, and have 0 or more digits after it.
Counting the occurrences of \d will find the number of digits in the string.
Counting the occurrences of \d+ will find the number of integers in the string.
I.E.
123 456 789
Has 9 digits, but 3 integers.
\d means any digit from 0 to 9, the + says "one or more times".
As long as your numbers are single digit there is no difference, but in the string "I have 23 cows" and \d would match 2 alone whereas \d+ would match 23.

How to match digit in middle of a string efficiently in javascript?

I have strings like
XXX-1234
XXXX-1234
XX - 4321
ABCDE - 4321
AB -5677
So there will be letters at the beginning. then there will be hyphen. and then 4 digits. Number of letters may vary but number of digits are same = 4
Now I need to match the first 2 positions from the digits. So I tried a long process.
temp_digit=mystring;
temp_digit=temp_digit.replace(/ /g,'');
temp_digit=temp_digit.split("-");
if(temp_digit[1].substring(0,2)=='12') {}
Now is there any process using regex / pattern matching so that I can do it in an efficient way. Something like string.match(regexp) I'm dumb in regex patterns. How can I find the first two digits from 4 digits from above strings ? Also it would be great it the solution can match digits without hyphens like XXX 1234 But this is optional.
Try a regular expression that finds at least one letter [a-zA-Z]+, followed by some space if necessary \s*, followed by a hyphen -, followed by some more space if necessary \s*. It then matches the first two digits \d{2} after the pattern.:
[a-zA-Z]+\s*-\s*(\d{2})
may vary but number of digits are same = 4
Now I need to match the first 2 positions from the digits.
Also it would be great it the solution can match digits without hyphens like XXX 1234 But this is optional.
Do you really need to check it starts with letters? How about matching ANY 4 digit number, and capturing only the first 2 digits?
Regex
/\b(\d{2})\d{2}\b/
Matches:
\b a word boundary
(\d{2}) 2 digits, captured in group 1, and assigned to match[1].
\d{2} 2 more digits (not captured).
\b a word boundary
Code
var regex = /\b(\d{2})\d{2}\b/;
var str = 'ABCDE 4321';
var result = str.match(regex)[1];
document.body.innerText += result;
If there are always 4 digits at the end, you can simply slice it:
str.trim().slice(-4,-2);
here's a jsfiddle with the example strings:
https://jsfiddle.net/mckinleymedia/6suffmmm/

Categories