Regex pattern search starts with 2 letters OR 2 numbers - javascript

I'm writing a javascript function to detect a correct entry into the database before sending it. The variable must start with either 2 digits OR 2 letters followed by 2 more letters then 3 digits. I can make each regex work independently but I want to do this in one statement. I've tried /^[A-Z]{2}|^[0-9]{2}[A-Z]{2}\d{3}$/ with no luck.
var valL = /^[A-Z]{2}[A-Z]{2}\d{3}$/;letter
var valj = /^[0-9]{2}[A-Z]{2}\d{2}$/;digits

You just need to group your alternation.
/^([A-Z]{2}|[0-9]{2})[A-Z]{2}\d{3}$/
otherwise you match only the left or the right side of the alternation.

Following regex should work:
/^(?:[A-Z]{2}|\d{2})[A-Z]{2}\d{3}$/i

Related

How can I write the Javascript Regular Expression pattern to handle these conditions

In My exercise, I'm given a task to write a regular expression pattern that validates username input for storage into database.
Usernames can only use alpha-numeric characters.
The only numbers in the username have to be at the end. There can be zero or more of them at the end. Username cannot start with the number.
Username letters can be lowercase and uppercase.
Usernames have to be at least two characters long. A two-character username can only use alphabet letters as characters.
I succeeded to pass all tests except one
A1 is not supposed to match the patern
let userCheck = /^[A-Za-z]+\w\d*$/;
let result = userCheck.test(username);
You can use an alternation after ^[a-z] the first letter to require either [a-z]+ one or more letters followed by \d* any amount of digits | OR \d{2,} two or more digits up to $ end of the string.
let userCheck = /^[a-z](?:[a-z]+\d*|\d{2,})$/i;
See this demo at regex101 - Used with the i-flag (ignore case) to shorten [A-Za-z] to [a-z].
PS: Just updated my answer at some late cup of coffee ☕🌙. Had previously misread the question and removed my answer in meanwhile. I would also have missed the part with e.g. Z97 which I just read at the other answers comments. It's much more of a challenge than at first glance... obviously :)
Edit:
My first answer did not fully solve the task. This regex does:
^([A-Za-z]{2}|[A-Za-z]\w{2,})$
it matches either two characters, or one character followed by at least two characters and/or digits (\w == [A-Za-z0-9]). See the demo here: https://regex101.com/r/sh6UpX/1
First answer (incorrect)
This works for your description:
let userCheck = /^[A-Za-z]{2,}\d*$/;
let result = userCheck.test(username);
Let me explain what went wrong in your regex:
/^[A-Za-z]+\w\d*$/
You correctly match, that the first character is only a letter. The '+' however only ensures, that it is matched at least one time. If you want to match something an exact number of times, you can append '{x}' to your match-case. If you rather want to match a minimum and maximum amount of times, you can append '{min, max}'. In your case, you only have a lower limit (2 times), so the max stays empty and means unlimited times: {2,}
After your [2 - unlimited] letters, you want to have [0 - unlimited] numbers. '\w' also matches letters, so we can just remove it. The end of your regex was correct, as '\d' matches any digit, and '*' quantifies the previous match for the range [0 - unlimited].
I recommend using regex101.com for testing and developing regex patterns. You can test your strings and get very good documentation and explanation about all the tags. I added my regex with some example strings to this link:
https://regex101.com/r/qPmwhG/1
The strings that match will be highlighted, the others stay without highlighting.

Regex exact match on number, not digit

I have a scenario where I need to find and replace a number in a large string using javascript. Let's say I have the number 2 and I want to replace it with 3 - it sounds pretty straight forward until I get occurrences like 22, 32, etc.
The string may look like this:
"note[2] 2 2_ someothertext_2 note[32] 2finally_2222 but how about mymomsays2."
I want turn turn it into this:
"note[3] 3 3_ someothertext_3 note[32] 3finally_2222 but how about mymomsays3."
Obviously this means .replace('2','3') is out of the picture so I went to regex. I find it easy to get an exact match when I am dealing with string start to end ie: /^2$/g. But that is not what I have. I tried grouping, digit only, wildcards, etc and I can't get this to match correctly.
Any help on how to exactly match a number (where 0 <= number <= 500 is possible, but no constraints needed in regex for range) would be greatly appreciated.
The task is to find (and replace) "single" digit 2, not embedded in
a number composed of multiple digits.
In regex terms, this can be expressed as:
Match digit 2.
Previous char (if any) can not be a digit.
Next char (if any) can not be a digit.
The regex for the first condition is straightforward - just 2.
In other flavours of regex, e.g. PCRE, to forbid the previous
char you could use negative lookbehind, but unfortunately Javascript
regex does not support it.
So, to circumvent this, we must:
Put a capturing group matching either start of text or something
other than a digit: (^|\D).
Then put regex matching just 2: 2.
The last condition, fortunately, can be expressed as negative lookahead,
because even Javascript regex support it: (?!\d).
So the whole regex is:
(^|\D)2(?!\d)
Having found such a match, you have to replace it with the content
of the first capturing group and 3 (the replacement digit).
You can use negative look-ahead:
(\D|^)2(?!\d)
Replace with: ${1}3
If look behind is supported:
(?<!\d)2(?!\d)
Replace with: 3
See regex in use here
(\D|\b)2(?!\d)
(\D|\b) Capture either a non-digit character or a position that matches a word boundary
(?!\d) Negative lookahead ensuring what follows is not a digit
Alternations:
(^|\D)2(?!\d) # Thanks to #Wiktor in the comments below
(?<!\d)2(?!\d) # At the time of writing works in Chrome 62+
const regex = /(\D|\b)2(?!\d)/g
const str = `note[2] 2 2_ someothertext_2 note[32] 2finally_2222 but how about mymomsays2.`
const subst = "$13"
console.log(str.replace(regex, subst))

Javascript - Matching a hyphen in regex

I'm trying to match a string using regex (of which I am new to) but I can't get it to match.
These should be accepted:
GT-00-TRE
KK-10-HUH
JU-05-OPR
These should not:
HTH-00-AS
HM-99-ASD
NM-05-AK
So the pattern goes 2 letters, hyphen, 2 digits (between 00 and 11 inclusive), hyphen, 3 letters.
So far the best I can come up with is:
var thePattern = /^[a-z]{2}[-][00-11][-][a-z]{3}$/gi;
I can't help but feel that I'm pretty close.
Can anyone give me any pointers?
Thanks.
This should be what you need:
var thePattern = /^[a-z]{2}[-](0\d|1[0-1])[-][a-z]{3}$/gi;
In order to do a range 00-11, you have to say "(0 followed by 0-9) or (1 followed by 0 or 1)". This is because specifying a range within [] only works for single digits. Luckily your case is pretty simple, otherwise it could get quite complex to work around that.
Your regex is OK, but for one thing: the digits matching is a bit more complex
(0\d|10|11)
you want to match a zero followed by a digit (\d) OR (|) a ten OR a eleven.
Something in square brackets represents just a single character in a range. [0-5] means any single digit between 0 and 5, [a-q] means any lowercase letter from a to q. There's no such thing as [00-11] because it would require to work on more than one character at a time.

Javascript RegEx not returning false as expected

Not a big user of RegEx - never really understood them! However, I feel the best way to check input for a username field would be with one that only allows Letters (upper or lower), numbers and the _ character, and must start with a letter as per the site policy. The My RegEx and code is as such:
var theCheck = /[a-zA-Z]|\d|_$/g;
alert(theCheck.test(theUsername));
Despite trying with various combinations, everything is returning "true".
Can anyone help?
Your regex is saying "does theUsername contain a letter, digit, or end with underscore".
Try this instead:
var theCheck = /^[a-z]([a-z_\d]*)$/i; // the "i" is "ignore case"
This says "theUsername starts with a letter and only contains letters, digits, or underscores".
Note: I don't think you need the "g" here, that means "all matches". We just want to test the whole string.
How about something like this:
^([a-zA-Z][a-zA-Z0-9_]{3,})$
To explain the entire pattern:
^ = Makes sure that the first pattern in brackets is at the beginning
() = puts the entire pattern in a group in case you need to pull it out and not just validate
a-zA-Z0-9_ = matches your character allowances
$ = Makes sure that this must be the entire line
{3,} = Makes sure there are a minimum of 3 characters.
You can add a number after the comma for a character limit max
You could also use a +, which would merely enforce at least one character match the second pattern. A * would not enforce any lengths
Use this as your regex:
^[A-Za-z][a-zA-Z0-9_]*$

Regex split string of numbers at finding of Alpha Characters

OK Regex is one of the most confusing things to me. I'm trying to do this in Javascript. I have a search field that the user will enter a series of characters. Codes are either:
999MC111
or just
999MC
There is ALWAYS 2 Alpha characters. BUT there may be 1-4 characters at the front and sometimes 1-4 characters at the end.
If the code ENDS with the Alpha characters, then I run a certain ajax script. If there are Numbers + 2 letters + numbers....it runs a different ajax script.
My struggle is I know \d is for 2 digits....but it may not always be 2 digits.
So what would my regex code be to split this into an array. or something.
I think correct regex would be (/^([0-9]+)([a-zA-z]+)([0-9]+)$/
But how do i make sure its ONLY 2 alpha characters in middle?
Thanks
You could use the regex /\d$/ to determine if it ends with a decimal.
\d matches a decimal character, and $ matches the end of the string. The / characters enclose the expression.
Try running this in your javascript console, line by line.
var values = ['999MC111', '999MC', '999XYZ111']; // some test values
// does it end in digits?
!!values[0].match(/\d$/); // evaluates to true
!!values[1].match(/\d$/); // evaluates to false
To specify the exact number of tokens you must use brackets {}, so if you know that there are 2 alphabetic tokens you put {2}, if you know that there could be 0-4 digits you put {0,4}
^([0-9]{0,4})([a-zA-z]{2})([0-9]{0,4})$
The above RegEx evaluates as follows:
999MC ---> TRUE
999MC111 --> TRUE
999MAC111 ---> FALSE
MC ---> TRUE
The splitting of the expression into capturing groups is done by means of grouping subexpressions into parentheses
As you can see in the following link:
http://regexr.com?2vfhv
you obtain this:
3 capturing groups:
group 1: ([0-9]{0,4})
group 2: ([a-zA-z]{2})
group 3: ([0-9]{0,4})
The regex /^\d{1,4}[a-zA-Z]{2}\d{0,4}$/ matches a series of 1-4 digits, followed by a series of 2 alpha characters, followed by another series of 0-4 digits.
This regex: /^\d{1,4}[a-zA-Z]{2}$/ matches a series of 1-4 digits, followed only by 2 alpha characters.
Ok so I didnt really care about the middle 2 characters....all that really mattered was the 1st set of numbers and last set of numbers (if any).
So essentially I just needed to deal with digits. So I did this:
var lead = '123mc444'; //For example purposes
var regex = /(\d+)/g;
var result = (lead.match(regex));
var memID = result[0]; //First set of numbers is member id
if(result[1] != undefined) {
var leadID = result[1];
}

Categories

Resources