I've got a simple regular expression:
[A-z]{2}[0-9]{3})$/g
inside the following:
regForm.submit(function(){
if ($.trim($('#new-usr').val()).match(/([A-z]{2}[0-9]{3})$/g)) {
alert('No');
return false;
}
});
This is correctly reading that something like 'ab123'
gives an alert and 'ab1234'
doesn't. However, 'abc123'
is still throwing the alert. I need it so it's only throwing the alert when it's just 2 letters followed by three numbers.
To get a string contains only numbers (0-9) with a optional + or - sign (e.g. +1223, -4567, 1223, 4567) we use the regular expression (/^[-+]?[0-9]+$/). Next, the match() method of the string object is used to match the said regular expression against the input value. Here is the complete web document.
?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).
The [0-9] expression is used to find any character between the brackets. The digits inside the brackets can be any numbers or span of numbers from 0 to 9.
The regular expression [A-Z][a-z]* matches any sequence of letters that starts with an uppercase letter and is followed by zero or more lowercase letters.
Try /^[A-z]{2}[0-9]{3}$/g
instead.
You need to specify that the whole string needs to be matched. Otherwise you get the highlighted part matched: abc123.
(I omitted the ()
's, because you don't really need the group.)
BTW, are you sure that you want [A-z]
and not just [A-Za-z]
?
The character class [A-z]
is probably not what you need.
Why?
The character class [A-z]
matches some non-alphabetical characters like [
, ]
among others.
JS fiddle link to prove this.
This W3school tutorial recommends it incorrectly.
If you need only lowercase letters use [a-z]
If you need only uppercase letters use [A-Z]
If you need both use: [a-zA-Z]
If you want to match a string if it has 2 letters followed by 3 digits anywhere in the string, just remove the end anchor $
from your pattern:
[a-z]{2}[0-9]{3}
If you want to match a string if it has 2 letters followed by 3 digits and nothing else use both start anchor ^
and end anchor $
as
^[a-z]{2}[0-9]{3}$
Alternatively you can use:
/\b([A-z]{2}[0-9]{3})\b/g
if your string contains multiple words and you are trying to match one word.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With