Regex for word and 2 numbers? - javascript

I am trying to create a regex on an input string for a name and 2 numbers separated by a comma and another word(words in capital):
PETER 1,2 PARENT //valid
PETER 1,2 //invalid
PETER 1,PARENT //invalid
What would the regex for this be? The numbers range from 0-4.

/^[A-Z]+ [0-4],[0-4] [A-Z]+$/
^ // start match
[A-Z]+ // one or more capital letters
// one space
[0-4] // a number between 0 and 4
, // comma
[0-4] // a number between 0 and 4
// one space
[A-Z]+ // one or more capital letters
$ // end match

Did you even try?
.+\s\d+,\d+\s.+, that means;
1) .+ -> (any character except new line) match one or more
2) \s -> match space
3) \d+ -> (any digit) match one or more
4) , -> match comma
5) match 3, 2 and 1

Related

Validate a gsheet/excel relative range string using js regex

I want to validate a range using javascript
Any range that has $ symbol must say invalid
Any range string that has symbols other than : must say invalid
Accpetable characters are capital or small alphabets and 0-9 numbers
Some of the expected results
A0 // invalid range begins with 1
ZZ12 // valid
ZZ12: // invalid incorrectly terminated
:A11 // invalid incorrectly started
:1 // invalid incorrectly started
:A // invalid incorrectly started
A1 // valid
B1 // valid
A2 // valid
C:F // valid
A10:B10 // valid
A:B10 // valid
A10:B // valid
A:B // valid
10:10 // valid
AA1 // valid
AAA1 // valid
B9:B10 // valid
A // invalid incomplete range string
1 // invalid incomplete range string
B // invalid incomplete range string
20 // invalid only a number not allowed
# // invalid symbols not allowed
## // invalid symbols not allowed
I have tried with
["A0","ZZ12","ZZ12:",":A11",":1",":A","A1","B1","A2","C:F","A10:B10","A:B10","A10:B","A:B","10:10","AA1","AAA1","B9:B10","A","1","B","20","#","##"]
.map(zz=>{return zz + "--->" + /^[A-Z]?[0-9]?:[A-Z]?[0-9]?$/.test(zz)})
This solution should address all your requirements, also for non-zero numbers:
const regex = /^(?:[A-Z]+[1-9][0-9]*|[A-Z]+(?:[1-9][0-9]*)?:[A-Z]+(?:[1-9][0-9]*)?|[1-9][0-9]*:[1-9][0-9]*)$/;
["A0","ZZ12","ZZ12:",":A11",":1",":A","A1","B1","A2","C:F","A10:B10","A:B10","A10:B","A:B","10:10","1:999","0:1","AA1","AAA1","B9:B10","A","1","B","20","#","##"
].map(str => {
//let valid = regex.test(str);
let valid = str.match(regex);
console.log(str, '==>', valid ? 'ok' : 'invalid');
});
Explanation of regex:
^(?: -- start of string and non-capture group start
[A-Z]+[1-9][0-9]* -- 1+ letters, number starting from 1
| -- logical or
[A-Z]+(?:[1-9][0-9]*)?:[A-Z]+(?:[1-9][0-9]*)? -- 1+ letters, optional number starting from 1, :, 1+ letters, optional number starting from 1
| -- logical or
[1-9][0-9]*:[1-9][0-9]* -- 1+ letters, number starting from 1, :, 1+ letters, number starting from 1
)$ -- end of non-capture group and string
With your shown samples please try following regex and JS code. Here is the Online Demo for used regex.
const regex = /^(?:[a-zA-Z]+\d*:[a-zA-Z]+\d*|[a-zA-Z]+[1-9]+\d*|\d+:\d+)$/;
[
"A0",
"ZZ12",
"ZZ12:",
":A11",
":1",
":A",
"A1",
"B1",
"A2",
"C:F",
"A10:B10",
"A:B10",
"A10:B",
"A:B",
"10:10",
"AA1",
"AAA1",
"B9:B10",
"A",
"1",
"B",
"20",
"#",
"##",
"$"
].forEach(element =>
console.log(`${element} ----> ${regex.test(element)}`)
);
Explanation: Adding detailed explanation for above used regex.
^ ##Checking from starting of value here.
(?: ##Starting one and only non-capturing group here.
[a-zA-Z]+\d*: ##matching 1 or more alphabets followed by 0 or more digits followed by colon.
[a-zA-Z]+\d* ##matching 1 or more alphabets followed by 0 or more digits here.
| ##Putting OR condition here.
[a-zA-Z]+[1-9]+\d* ##Matching 1 or more alphabets followed by 1 or more digits.
| ##Putting OR condition here.
\d+:\d+ ##Matching 1 or more digits followed by colon followed by 1 or more digits.
)$ ##Closing non-capturing group at the end of the value here.
Try this:
^([A-Za-z])\1*(?:[1-9]\d*)*:([A-Za-z])\2*(?:[1-9]\d*)*$|^(?:([A-Za-z])\3*|[1-9]\d*:)[1-9]\d*$
Explanation:
First part ^([A-Za-z])\1*(?:[1-9]\d*)*:([A-Za-z])\2*(?:[1-9]\d*)*$ to match things like C:F, A10:B10, A:B10, A10:B, A:B and B9:B10.
^ start of the line/string.
([A-Za-z]) Group1: [A-Za-z] one letter captured by the first group, and the value inside the first capturing group can be accessed by \1.
\1*, \1 the value inside the first capturing group, * match zero or more of the value inside the first capturing group, for example if the value is A, then things like AAA will be matched.
(?:[1-9]\d*)* non-capturing group, [1-9] one digit from 1 to 9, followed by \d* zero or more digits from 0 to 9, and that group will be repeated between zero or more times.
: a literal colon :.
([A-Za-z]) Group2:[A-Za-z] the same as before with Group1, but now we can access the value inside the second capturing group by \2.
\2* the same as before with \1*, but now the value is the one inside the second capturing group.
(?:[1-9]\d*)* the same as before.
$ the end of the line/string.
| the alternation operator it is like Boolean OR, to match other cases.
Second part ^(?:([A-Za-z])\3*|[1-9]\d*:)[1-9]\d*$ to match things like A1, B1, A2 and 10:10.
^ the start of the line/string.
(?:([A-Za-z])\3*|[1-9]\d*:) non-capturing group contains:
([A-Za-z]) Group3:[A-Za-z] the same as before with Group1 and Group2, but now we can access the value inside the third capturing group by \3.
\3* the same as before with \1* and \2*, but now the value is the one inside the third capturing group.
| the alternation operator it is like Boolean OR, to match other cases.
[1-9]\d*: one digit from 1 to 9, followed by zero or more digits from 0 to 9, followed by a literal :.
[1-9]\d* one digit from 1 to 9, followed by zero or more digits from 0 to 9.
$ the end of the line/string.
See regex demo

Regex for match beginning with 2 letters and ending with 3 letters

Example input:
'Please find the ref AB45676785567XYZ. which is used to identify reference number'
Example output:
'AB45676785567XYZ'
I need a RegExp to return the match exactly matching my requirements; i.e. the substring where the first 2 and last 3 characters are letters.
The first 2 and last 3 letters are unknown.
I've tried this RegExp:
[a-zA-Z]{2}[^\s]*?[a-zA-Z]{3}
But it is not matching as intended.
Your current RegExp matches the following words marked with code blocks:
Please find the ref AB45676785567XYZ. which is used to identify reference number
This is because your RegExp, [a-zA-Z]{2}[^\s]*?[a-zA-Z]{3}, is asking for:
[a-zA-Z]{2} Begins with 2 letters (either case)
[^\s]*? Contains anything that isn't a whitespace
[a-zA-Z]{3} Ends with 3 letters (either case)
In your current example, restricting the letters to uppercase only would match only the match you seek:
[A-Z]{2}[^\s]+[A-Z]{3}
Alternatively, requiring numbers between the 2 beginning and 3 ending letters would also produce the match you want:
[a-zA-Z]{2}\d+[a-zA-Z]{3}
What is really important here, is word boundaries \b, try: \b[a-zA-Z]{2}\w+[a-zA-Z]{3}\b
Explanation:
\b - word boundary
[a-zA-Z]{2} - match any letter, 2 times
\w+ - match one or more word characters
[a-zA-Z]{3} - match any letter, 3 times
\b - word boundary
Demo
CAUTION your requirements are amibgious, as any word consisting of 5 or more letters would match the pattern
Start with 2 letters :
[a-zA-Z]{2}
Digits in the middle :
\d+
Finish with 3 letters :
[a-zA-Z]{3}
Full Regex :
[a-zA-Z]{2}\d+[a-zA-Z]{3}
If the middle text is Alpha-Numeric, you can use this :
[A-Z]{2}[^\s]+[A-Z]{3}

Validating userName using Regex

The only numbers in the username have to be at the end. There can be zero or more of them at the end.
Username letters can be lowercase and uppercase.
Usernames have to be at least two characters long. A two-letter username can only use alphabet letter characters.
I'm trying with this but I'm stalled. /\d+$\w+/gi
/^[a-z]{2,}\d*$/i is:
^ : the begining
[a-z] : a character (a to z), you can add as many allowed characters as you want
{2,} : at least 2 of them
\d* : 0 or more digits
$ : the end
i : ignore case sensetivity (both lowercases and uppercases are allowed)
Username having characters and digit and min 2 character long
/^[a-zA-Z]{2,}\d*$/i
Test result :
UserNam9 = pass
9username = fail
Userna99 = pass
usernameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee = pass
Us = pass
U = fail
/^[A-z]{2,}[A-z0-9]{0,}$/
/^ // start of line
[A-z]{2,} //alphabet characters 2 or more
[A-z0-9]{0,} //numbers and alphabet
$/ // end of line
You've missed cases when there's a letter in the start, followed by 2 or more numbers.
U99 = fail
d345 = fail
My solution passes these tests, as well:
/^[a-z]{2,}\d*$|(?=\w{3,})^[a-z]{1,}\d+$/i
Using positive lookahead I am making sure that in the second case there are at least 3 alphanumeric characters.
Simplified version of /^[a-z]{2,}\d*$|(?=\w{3,})^[a-z]{1,}\d+$/i:
/^\D(\d{2,}|\D+)\d*$/i
Code explanation:
^ - start of input
\D - first character is a letter
\d{2,} - ends with two or more numbers
| - or
\D+ - has one or more letters next
\d* - and ends with zero or more numbers
$ - end of input
i - ignore case of input
This is my answer, it passed all the tests:
/^[a-z][a-z]+\d*$|^[a-z]\d{2,}$/i
First Part: 2 letters (or more) and zero or more numbers
Or
Second Part: 1 letter and 2 or more numbers

Regular Expression with exactly 2 uppercase letters and 3 numbers

I need to match words that contains exactly 2 uppercase letters and 3 numbers. Numbers and uppercase letters can be at any positions in the word.
HelLo1aa2s3d: true
WindowA1k2j3: true
AAAsjs21js1: false
ASaaak12: false
My regex attempt, but only matches exactly 2 uppercase letters:
([a-z]*[A-Z]{1}[a-z]*){2}
You can use regex lookaheads:
/^(?=(?:.*[A-Z].*){2})(?!(?:.*[A-Z].*){3,})(?=(?:.*\d.*){3})(?!(?:.*\d.*){4,}).*$/gm
Explanation:
^ // assert position at beginning of line
(?=(?:.*[A-Z].*){2}) // positive lookahead to match exactly 2 uppercase letters
(?!(?:.*[A-Z].*){3,}) // negative lookahead to not match if 3 or more uppercase letters
(?=(?:.*\d.*){3}) // positive lookahead to match exactly 3 digits
(?!(?:.*\d.*){4,}) // negative lookahead to not match if 4 or more digits
.* // select all of non-newline characters if match
$ // end of line
/gm // flags: "g" - global; "m" - multiline
Regex101
I think, you need just one lookahead.
^(?=(?:\D*\d){3}\D*$)(?:[^A-Z]*[A-Z]){2}[^A-Z]*$
\d is a short for digit. \D is the negation of \d and matches a non-digit
(?= opens a positive lookahead. (?: opens a non capturing group.
At ^ start (?=(?:\D*\d){3}\D*$) looks ahead for exactly three digits until $ the end.
If the condition succeeds (?:[^A-Z]*[A-Z]){2}[^A-Z]* matches a string with exactly two upper alphas until $ end. [^ opens a negated character class.
Demo at regex101
If you want to allow only alphanumeric characters, replace [^A-Z] with [a-z\d] like in this demo.
The solution using String.match function:
function checkWord(word) {
var numbers = word.match(/\d/g), letters = word.match(/[A-Z]/g);
return (numbers.length === 3 && letters.length === 2) || false;
}
console.log(checkWord("HelLo1aa2s3d")); // true
console.log(checkWord("WindowA1k2j3")); // true
console.log(checkWord("AAAsjs21js1")); // false
console.log(checkWord("ASaaak12")); // false
Without lookahead, pure regex:
http://regexr.com/3ddva
Basically, just checks every case.

Which RegExp matches a colon between two pairs of digits?

Using .match(), .replace() and other RegExp-things I need to make the RegExp, which could change those example input strings:
'123'
'1234'
'qqxwdx1234sgvs'
'weavrt123adcsd'
to normal output ones:
'1:23'
'12:34'
(So, three-digit clusters must be x:xx formatted).
You can use String.prototype.replace() with a regex that matches 1 or 2 digits followed by 2 digits. $1 is the first captured group (1 or 2 digits), $2 is the second captured group (2 digits). $1:$2 is the replacement, it replaces the matched text with the first captured group ($1) followed by a colon (:), followed by the second captured group ($2).
var string = '123';
string = string.replace(/^(\d{1,2})(\d{2})$/, '$1:$2');
console.log(string); // "1:23"
Explanation of the regex:
^ the beginning of the string
( group and capture to $1:
\d{1,2} digits (0-9) (between 1 and 2 times
(matching the most amount possible))
) end of $1
( group and capture to $2:
\d{2} digits (0-9) (2 times)
) end of $2
$ before an optional \n, and the end of the
string

Categories

Resources