Java Reference
In-Depth Information
This means you want to match any character that is not one of the characters specified inside the
square brackets.
2.
You add a‐z , which specifies any character in the range a through z:
[^a-z]
So far, your regular expression matches any character that is not between a and z. Note that,
because you added the if to the end of the expression definition, you've made the pattern case‐
insensitive. So your regular expression actually matches any character not between A and Z or a
and z.
3.
You add \d to indicate any digit character, or any character between 0 and 9:
[^a-z\d]
4.
Your expression matches any character that is not between a and z, A and Z, or 0 and 9. You
decide that a space is valid, so you add that inside the square brackets:
[^a-z\d ]
Putting this all together, you have a regular expression that matches any character that is not a
letter, a digit, or a space.
5.
On the second and final line of the function, you use the RegExp object's test() method to return
a value:
return !(myRegExp.test(text));
The test() method of the RegExp object checks the string passed as its parameter to see if the
characters specified by the regular expression syntax match anything inside the string. If they do,
true is returned; if not, false is returned. Your regular expression matches the first invalid character
found, so if you get a result of true , you have an invalid passphrase. However, it's a bit illogical for an
is _ valid function to return true when it's invalid, so you reverse the result returned by adding the
NOT operator ( ! ).
Previously you saw the two‐line validity‐checker function using regular expressions. Just to show how much
more coding is required to do the same thing without regular expressions, here is a second function that
does the same thing as isValid() but without regular expressions:
function isValid2(text) {
var returnValue = true;
var validChars = "abcdefghijklmnopqrstuvwxyz1234567890 ";
for (var charIndex = 0; charIndex < text.length;charIndex++) {
if (validChars.indexOf(text.charAt(charIndex).toLowerCase()) < 0) {
returnValue = false;
break;
}
}
return returnValue;
}
Search WWH ::




Custom Search