6.5
To understand why, remember that or operates on truth values, so when you say “or 2”, it begins with
the question “is 2 true or false?” By convention, any number that is not zero is treated as “true”, so “or 2”
makes the expression always true regardless of the value of num. On the other hand, the program on the
right produced the desired result: “or n is 2” only makes the expression true when the number is 2.
Another way to think about the difference is with precedence of operators. The word “or” has lower
precedence than the word “is”, so the expression on the left reads like this: ((n is 1) or 2) and the
expression on the right reads like this: ((n is 1) or (n is 2)).
Testing Strings Using Pattern Matching
Text strings can also be tested to create Boolean values. It is common to test strings by comparing them
exactly (looking at their length) or by testing if the string matches a pattern using the “match” method.
Pattern matching can be used to determine if a string contains a particular pattern of letters within it.
The following table shows several examples.
x is exactly equal to the string "pear"
x has exactly 6 characters
x contains the substring “pp”.
x contains the substring “pea”
x contains the substring “PEA”
x contains the substring “Pea”, ignoring case
x contains “pea” at the start of the string
x contains “ear” at the end of the string
x contains “a” followed by either “p” or “ch”
x contains “a”, then zero or more “p”, then “e”
The patterns used between the “/” symbols are called regular expressions.
A regular expression can be used to test whether a string contains a fixed pattern, for example whether it
contains the letters “pp”. Normally regular expressions are case-sensitive, so “PEA” does not match
“pea”, but putting an “i” after the regular expression makes it case-insensitive.
Regular expression patterns have several powerful features. For example, in a regular expression, “^”
matches the beginning of the string, “$” matches the end of the string, “(one|other)” is used to match
alternatives, and “*” allows a sub-pattern to be repeated zero or more times.
Although the types of patterns shown above are enough for most situations, regular expressions have
several more features. There are many excellent resources about regular expressions on the Internet if
you search for “regular expression lessons”. When exploring, it is important to know that the symbols
used in regular expression patterns are standardized, and the same pattern language is used in
JavaScript, CoffeeScript, Python, Perl, Java, C# and other languages.