Java Reference
In-Depth Information
This is probably as small as the non-regular expression version can be, and yet it's still several lines
longer than isValid() .
The principle of this function is similar to that of the regular expression version. You have a variable,
validChars , which contains all the characters you consider to be valid. You then use the charAt()
method in a for loop to get each character in the passphrase string and check whether it exists in your
validChars string. If it doesn't, you know you have an invalid character.
In this example, the non-regular expression version of the function is 10 lines, but with a more complex
problem you could find it takes 20 or 30 lines to do the same thing a regular expression can do in just a few.
Back to your actual code: you use an if...else statement to display the appropriate message to the
user. If the passphrase is valid, an alert box tells the user that all is fine:
if (isValid(input)) {
alert("Your passphrase contains only valid characters");
}
If it isn't, another alert box tells users that their text was invalid:
else {
alert("Your passphrase contains one or more invalid characters");
}
repetition Characters
Regular expressions include something called repetition characters, which are a means of specifying
how many of the last item or character you want to match. This proves very useful, for example,
if you want to specify a phone number that repeats a character a specific number of times. The
following table lists some of the most common repetition characters and what they do:
speCial CharaCter
meaning
example
{n}
Match n of the previous item.
x{2} matches xx.
{n,}
Match n or more of the previous
item.
x{2,} matches xx, xxx, xxxx, xxxxx,
and so on.
{n,m}
Match at least n and at most m of
the previous item.
x{2,4} matches xx, xxx, and xxxx.
?
Match the previous item zero or
one time.
x? matches nothing or x.
+
Match the previous item one or
more times.
x+ matches x, xx, xxx, xxxx, xxxxx,
and so on.
*
Match the previous item zero or
more times.
x* matches nothing, or x, xx, xxx,
xxxx, and so on.
 
Search WWH ::




Custom Search