mirror of
https://github.com/apachecn/eloquent-js-3e-zh.git
synced 2025-05-23 20:02:20 +00:00
788 lines
56 KiB
Diff
788 lines
56 KiB
Diff
diff --git a/2ech9.md b/3ech9.md
|
||
index cbbeb4e..7a67f2e 100644
|
||
--- a/2ech9.md
|
||
+++ b/3ech9.md
|
||
@@ -4,37 +4,35 @@
|
||
>
|
||
> <footer>Jamie Zawinski</footer>
|
||
|
||
-> Yuan-Ma said, ‘When you cut against the grain of the wood, much strength is needed. When you program against the grain of a problem, much code is needed.'
|
||
+> Yuan-Ma said, ‘When you cut against the grain of the wood, much strength is needed. When you program against the grain of the problem, much code is needed.'
|
||
>
|
||
> <footer>Master Yuan-Ma, <cite>The Book of Programming</cite></footer>
|
||
|
||
-Programming tools and techniques survive and spread in a chaotic, evolutionary way. It's not always the pretty or brilliant ones that win but rather the ones that function well enough within the right niche—for example, by being integrated with another successful piece of technology.
|
||
+Programming tools and techniques survive and spread in a chaotic, evolutionary way. It's not always the pretty or brilliant ones that win but rather the ones that function well enough within the right niche or happen to be integrated with another successful piece of technology.
|
||
|
||
-In this chapter, I will discuss one such tool, _regular expressions_. Regular expressions are a way to describe patterns in string data. They form a small, separate language that is part of JavaScript and many other languages and tools.
|
||
+In this chapter, I will discuss one such tool, _regular expressions_. Regular expressions are a way to describe patterns in string data. They form a small, separate language that is part of JavaScript and many other languages and systems.
|
||
|
||
Regular expressions are both terribly awkward and extremely useful. Their syntax is cryptic, and the programming interface JavaScript provides for them is clumsy. But they are a powerful tool for inspecting and processing strings. Properly understanding regular expressions will make you a more effective programmer.
|
||
|
||
## Creating a regular expression
|
||
|
||
-A regular expression is a type of object. It can either be constructed with the `RegExp` constructor or written as a literal value by enclosing the pattern in forward slash (`/`) characters.
|
||
+A regular expression is a type of object. It can either be constructed with the `RegExp` constructor or written as a literal value by enclosing a pattern in forward slash (`/`) characters.
|
||
|
||
```
|
||
-var re1 = new RegExp("abc");
|
||
-var re2 = /abc/;
|
||
+let re1 = new RegExp("abc");
|
||
+let re2 = /abc/;
|
||
```
|
||
|
||
-Both of these regular expression objects represent the same pattern: an _a_ character followed by a _b_ followed by a _c_.
|
||
+Both of those regular expression objects represent the same pattern: an _a_ character followed by a _b_ followed by a _c_.
|
||
|
||
When using the `RegExp` constructor, the pattern is written as a normal string, so the usual rules apply for backslashes.
|
||
|
||
The second notation, where the pattern appears between slash characters, treats backslashes somewhat differently. First, since a forward slash ends the pattern, we need to put a backslash before any forward slash that we want to be _part_ of the pattern. In addition, backslashes that aren't part of special character codes (like `\n`) will be _preserved_, rather than ignored as they are in strings, and change the meaning of the pattern. Some characters, such as question marks and plus signs, have special meanings in regular expressions and must be preceded by a backslash if they are meant to represent the character itself.
|
||
|
||
```
|
||
-var eighteenPlus = /eighteen\+/;
|
||
+let eighteenPlus = /eighteen\+/;
|
||
```
|
||
|
||
-Knowing precisely what characters to backslash-escape when writing regular expressions requires you to know every character with a special meaning. For the time being, this may not be realistic, so when in doubt, just put a backslash before any character that is not a letter, number, or whitespace.
|
||
-
|
||
## Testing for matches
|
||
|
||
Regular expression objects have a number of methods. The simplest one is `test`. If you pass it a string, it will return a Boolean telling you whether the string contains a match of the pattern in the expression.
|
||
@@ -48,9 +46,9 @@ console.log(/abc/.test("abxde"));
|
||
|
||
A regular expression consisting of only nonspecial characters simply represents that sequence of characters. If _abc_ occurs anywhere in the string we are testing against (not just at the start), `test` will return `true`.
|
||
|
||
-## Matching a set of characters
|
||
+## Sets of characters
|
||
|
||
-Finding out whether a string contains _abc_ could just as well be done with a call to `indexOf`. Regular expressions allow us to go beyond that and express more complicated patterns.
|
||
+Finding out whether a string contains _abc_ could just as well be done with a call to `indexOf`. Regular expressions allow us to express more complicated patterns.
|
||
|
||
Say we want to match any number. In a regular expression, putting a set of characters between square brackets makes that part of the expression match any of the characters between the brackets.
|
||
|
||
@@ -65,7 +63,7 @@ console.log(/[0-9]/.test("in 1992"));
|
||
|
||
Within square brackets, a dash (`-`) between two characters can be used to indicate a range of characters, where the ordering is determined by the character's Unicode number. Characters 0 to 9 sit right next to each other in this ordering (codes 48 to 57), so `[0-9]` covers all of them and matches any digit.
|
||
|
||
-There are a number of common character groups that have their own built-in shortcuts. Digits are one of them: `\d` means the same thing as `[0-9]`.
|
||
+A number of common character groups have their own built-in shortcuts. Digits are one of them: `\d` means the same thing as `[0-9]`.
|
||
|
||
| `\d` | Any digit character |
|
||
| `\w` | An alphanumeric character (“word character”) |
|
||
@@ -78,21 +76,21 @@ There are a number of common character groups that have their own built-in short
|
||
So you could match a date and time format like 30-01-2003 15:20 with the following expression:
|
||
|
||
```
|
||
-var dateTime = /\d\d-\d\d-\d\d\d\d \d\d:\d\d/;
|
||
+let dateTime = /\d\d-\d\d-\d\d\d\d \d\d:\d\d/;
|
||
console.log(dateTime.test("30-01-2003 15:20"));
|
||
// → true
|
||
console.log(dateTime.test("30-jan-2003 15:20"));
|
||
// → false
|
||
```
|
||
|
||
-That looks completely awful, doesn't it? It has way too many backslashes, producing background noise that makes it hard to spot the actual pattern expressed. We'll see a slightly improved version of this expression [later](09_regexp.html#date_regexp_counted).
|
||
+That looks completely awful, doesn't it? Half of it is backslashes, producing a background noise that makes it hard to spot the actual pattern expressed. We'll see a slightly improved version of this expression [later](09_regexp.html#date_regexp_counted).
|
||
|
||
-These backslash codes can also be used inside square brackets. For example, `[\d.]` means any digit or a period character. But note that the period itself, when used between square brackets, loses its special meaning. The same goes for other special characters, such as `+`.
|
||
+These backslash codes can also be used inside square brackets. For example, `[\d.]` means any digit or a period character. But the period itself, between square brackets, loses its special meaning. The same goes for other special characters, such as `+`.
|
||
|
||
To _invert_ a set of characters—that is, to express that you want to match any character _except_ the ones in the set—you can write a caret (`^`) character after the opening bracket.
|
||
|
||
```
|
||
-var notBinary = /[^01]/;
|
||
+let notBinary = /[^01]/;
|
||
console.log(notBinary.test("1100100010100110"));
|
||
// → false
|
||
console.log(notBinary.test("1100100010200110"));
|
||
@@ -118,10 +116,10 @@ console.log(/'\d*'/.test("''"));
|
||
|
||
The star (`*`) has a similar meaning but also allows the pattern to match zero times. Something with a star after it never prevents a pattern from matching—it'll just match zero instances if it can't find any suitable text to match.
|
||
|
||
-A question mark makes a part of a pattern “optional”, meaning it may occur zero or one time. In the following example, the _u_ character is allowed to occur, but the pattern also matches when it is missing.
|
||
+A question mark makes a part of a pattern _optional_, meaning it may occur zero times or one time. In the following example, the _u_ character is allowed to occur, but the pattern also matches when it is missing.
|
||
|
||
```
|
||
-var neighbor = /neighbou?r/;
|
||
+let neighbor = /neighbou?r/;
|
||
console.log(neighbor.test("neighbour"));
|
||
// → true
|
||
console.log(neighbor.test("neighbor"));
|
||
@@ -130,36 +128,36 @@ console.log(neighbor.test("neighbor"));
|
||
|
||
To indicate that a pattern should occur a precise number of times, use curly braces. Putting `{4}` after an element, for example, requires it to occur exactly four times. It is also possible to specify a range this way: `{2,4}` means the element must occur at least twice and at most four times.
|
||
|
||
-Here is another version of the date and time pattern that allows both single- and double-digit days, months, and hours. It is also slightly more readable.
|
||
+Here is another version of the date and time pattern that allows both single- and double-digit days, months, and hours. It is also slightly easier to decipher.
|
||
|
||
```
|
||
-var dateTime = /\d{1,2}-\d{1,2}-\d{4} \d{1,2}:\d{2}/;
|
||
+let dateTime = /\d{1,2}-\d{1,2}-\d{4} \d{1,2}:\d{2}/;
|
||
console.log(dateTime.test("30-1-2003 8:45"));
|
||
// → true
|
||
```
|
||
|
||
-You can also specify open-ended ranges when using curly braces by omitting the number after the comma. So `{5,}` means five or more times.
|
||
+You can also specify open-ended ranges when using curly braces by omitting the number after the comma. So, `{5,}` means five or more times.
|
||
|
||
## Grouping subexpressions
|
||
|
||
-To use an operator like `*` or `+` on more than one element at a time, you can use parentheses. A part of a regular expression that is enclosed in parentheses counts as a single element as far as the operators following it are concerned.
|
||
+To use an operator like `*` or `+` on more than one element at a time, you have to use parentheses. A part of a regular expression that is enclosed in parentheses counts as a single element as far as the operators following it are concerned.
|
||
|
||
```
|
||
-var cartoonCrying = /boo+(hoo+)+/i;
|
||
+let cartoonCrying = /boo+(hoo+)+/i;
|
||
console.log(cartoonCrying.test("Boohoooohoohooo"));
|
||
// → true
|
||
```
|
||
|
||
The first and second `+` characters apply only to the second _o_ in _boo_ and _hoo_, respectively. The third `+` applies to the whole group `(hoo+)`, matching one or more sequences like that.
|
||
|
||
-The `i` at the end of the expression in the previous example makes this regular expression case insensitive, allowing it to match the uppercase _B_ in the input string, even though the pattern is itself all lowercase.
|
||
+The `i` at the end of the expression in the example makes this regular expression case insensitive, allowing it to match the uppercase _B_ in the input string, even though the pattern is itself all lowercase.
|
||
|
||
## Matches and groups
|
||
|
||
The `test` method is the absolute simplest way to match a regular expression. It tells you only whether it matched and nothing else. Regular expressions also have an `exec` (execute) method that will return `null` if no match was found and return an object with information about the match otherwise.
|
||
|
||
```
|
||
-var match = /\d+/.exec("one two 100");
|
||
+let match = /\d+/.exec("one two 100");
|
||
console.log(match);
|
||
// → ["100"]
|
||
console.log(match.index);
|
||
@@ -178,7 +176,7 @@ console.log("one two 100".match(/\d+/));
|
||
When the regular expression contains subexpressions grouped with parentheses, the text that matched those groups will also show up in the array. The whole match is always the first element. The next element is the part matched by the first group (the one whose opening parenthesis comes first in the expression), then the second group, and so on.
|
||
|
||
```
|
||
-var quotedText = /'([^']*)'/;
|
||
+let quotedText = /'([^']*)'/;
|
||
console.log(quotedText.exec("she said 'hello'"));
|
||
// → ["'hello'", "hello"]
|
||
```
|
||
@@ -194,15 +192,15 @@ console.log(/(\d)+/.exec("123"));
|
||
|
||
Groups can be useful for extracting parts of a string. If we don't just want to verify whether a string contains a date but also extract it and construct an object that represents it, we can wrap parentheses around the digit patterns and directly pick the date out of the result of `exec`.
|
||
|
||
-But first, a brief detour, in which we discuss the preferred way to store date and time values in JavaScript.
|
||
+But first, a brief detour, in which we discuss the built-in way to represent date and time values in JavaScript.
|
||
|
||
-## The date type
|
||
+## The Date class
|
||
|
||
-JavaScript has a standard object type for representing dates—or rather, points in time. It is called `Date`. If you simply create a date object using `new`, you get the current date and time.
|
||
+JavaScript has a standard class for representing dates—or rather, points in time. It is called `Date`. If you simply create a date object using `new`, you get the current date and time.
|
||
|
||
```
|
||
console.log(new Date());
|
||
-// → Wed Dec 04 2013 14:24:57 GMT+0100 (CET)
|
||
+// → Mon Nov 13 2017 16:19:11 GMT+0100 (CET)
|
||
```
|
||
|
||
You can also create an object for a specific time.
|
||
@@ -218,7 +216,7 @@ JavaScript uses a convention where month numbers start at zero (so December is 1
|
||
|
||
The last four arguments (hours, minutes, seconds, and milliseconds) are optional and taken to be zero when not given.
|
||
|
||
-Timestamps are stored as the number of milliseconds since the start of 1970, using negative numbers for times before 1970 (following a convention set by “Unix time”, which was invented around that time). The `getTime` method on a date object returns this number. It is big, as you can imagine.
|
||
+Timestamps are stored as the number of milliseconds since the start of 1970, in the UTC time zone. This follows a convention set by “Unix time”, which was invented around that time. You can use negative numbers for times before 1970\. The `getTime` method on a date object returns this number. It is big, as you can imagine.
|
||
|
||
```
|
||
console.log(new Date(2013, 11, 19).getTime());
|
||
@@ -227,29 +225,29 @@ console.log(new Date(1387407600000));
|
||
// → Thu Dec 19 2013 00:00:00 GMT+0100 (CET)
|
||
```
|
||
|
||
-If you give the `Date` constructor a single argument, that argument is treated as such a millisecond count. You can get the current millisecond count by creating a new `Date` object and calling `getTime` on it but also by calling the `Date.now` function.
|
||
+If you give the `Date` constructor a single argument, that argument is treated as such a millisecond count. You can get the current millisecond count by creating a new `Date` object and calling `getTime` on it or by calling the `Date.now` function.
|
||
|
||
-Date objects provide methods like `getFullYear`, `getMonth`, `getDate`, `getHours`, `getMinutes`, and `getSeconds` to extract their components. There's also `getYear`, which gives you a rather useless two-digit year value (such as `93` or `14`).
|
||
+Date objects provide methods like `getFullYear`, `getMonth`, `getDate`, `getHours`, `getMinutes`, and `getSeconds` to extract their components. Besides `getFullYear`, there's also `getYear`, which gives you a rather useless two-digit year value (such as `93` or `14`).
|
||
|
||
-Putting parentheses around the parts of the expression that we are interested in, we can now easily create a date object from a string.
|
||
+Putting parentheses around the parts of the expression that we are interested in, we can now create a date object from a string.
|
||
|
||
```
|
||
-function findDate(string) {
|
||
- var dateTime = /(\d{1,2})-(\d{1,2})-(\d{4})/;
|
||
- var match = dateTime.exec(string);
|
||
- return new Date(Number(match[3]),
|
||
- Number(match[2]) - 1,
|
||
- Number(match[1]));
|
||
+function getDate(string) {
|
||
+ let [_, day, month, year] =
|
||
+ /(\d{1,2})-(\d{1,2})-(\d{4})/.exec(string);
|
||
+ return new Date(year, month - 1, day);
|
||
}
|
||
-console.log(findDate("30-1-2003"));
|
||
+console.log(getDate("30-1-2003"));
|
||
// → Thu Jan 30 2003 00:00:00 GMT+0100 (CET)
|
||
```
|
||
|
||
+The `_` (underscore) binding is ignored, and only used to skip the full match element in the array returned by `exec`.
|
||
+
|
||
## Word and string boundaries
|
||
|
||
-Unfortunately, `findDate` will also happily extract the nonsensical date 00-1-3000 from the string `"100-1-30000"`. A match may happen anywhere in the string, so in this case, it'll just start at the second character and end at the second-to-last character.
|
||
+Unfortunately, `getDate` will also happily extract the nonsensical date 00-1-3000 from the string `"100-1-30000"`. A match may happen anywhere in the string, so in this case, it'll just start at the second character and end at the second-to-last character.
|
||
|
||
-If we want to enforce that the match must span the whole string, we can add the markers `^` and `<article. The caret matches the start of the input string, while the dollar sign matches the end. So, `/^\d+$/` matches a string consisting entirely of one or more digits, `/^!/` matches any string that starts with an exclamation mark, and `/x^/` does not match any string (there cannot be an _x_ before the start of the string).
|
||
+If we want to enforce that the match must span the whole string, we can add the markers `^` and `<article. The caret matches the start of the input string, whereas the dollar sign matches the end. So, `/^\d+$/` matches a string consisting entirely of one or more digits, `/^!/` matches any string that starts with an exclamation mark, and `/x^/` does not match any string (there cannot be an _x_ before the start of the string).
|
||
|
||
If, on the other hand, we just want to make sure the date starts and ends on a word boundary, we can use the marker `\b`. A word boundary can be the start or end of the string or any point in the string that has a word character (as in `\w`) on one side and a nonword character on the other.
|
||
|
||
@@ -260,7 +258,7 @@ console.log(/\bcat\b/.test("concatenate"));
|
||
// → false
|
||
```
|
||
|
||
-Note that a boundary marker doesn't represent an actual character. It just enforces that the regular expression matches only when a certain condition holds at the place where it appears in the pattern.
|
||
+Note that a boundary marker doesn't match an actual character. It just enforces that the regular expression matches only when a certain condition holds at the place where it appears in the pattern.
|
||
|
||
## Choice patterns
|
||
|
||
@@ -269,24 +267,26 @@ Say we want to know whether a piece of text contains not only a number but a num
|
||
We could write three regular expressions and test them in turn, but there is a nicer way. The pipe character (`|`) denotes a choice between the pattern to its left and the pattern to its right. So I can say this:
|
||
|
||
```
|
||
-var animalCount = /\b\d+ (pig|cow|chicken)s?\b/;
|
||
+let animalCount = /\b\d+ (pig|cow|chicken)s?\b/;
|
||
console.log(animalCount.test("15 pigs"));
|
||
// → true
|
||
console.log(animalCount.test("15 pigchickens"));
|
||
// → false
|
||
```
|
||
|
||
-Parentheses can be used to limit the part of the pattern that the pipe operator applies to, and you can put multiple such operators next to each other to express a choice between more than two patterns.
|
||
+Parentheses can be used to limit the part of the pattern that the pipe operator applies to, and you can put multiple such operators next to each other to express a choice between more than two alternatives.
|
||
|
||
## The mechanics of matching
|
||
|
||
-Regular expressions can be thought of as flow diagrams. This is the diagram for the livestock expression in the previous example:
|
||
+Conceptually, when you use `exec` or `test` the regular expression engine looks for a match in your string by trying to match the expression first from the start of the string, then from the second character, and so on until it finds a match or reaches the end of the string. It'll either return the first match that can be found or fail to find any match at all.
|
||
+
|
||
+To do the actual matching, the engine treats a regular expression something like a flow diagram. This is the diagram for the livestock expression in the previous example:
|
||
|
||
-
|
||
+<figure></figure>
|
||
|
||
-Our expression matches a string if we can find a path from the left side of the diagram to the right side. We keep a current position in the string, and every time we move through a box, we verify that the part of the string after our current position matches that box.
|
||
+Our expression matches if we can find a path from the left side of the diagram to the right side. We keep a current position in the string, and every time we move through a box, we verify that the part of the string after our current position matches that box.
|
||
|
||
-So if we try to match `"the 3 pigs"` with our regular expression, our progress through the flow chart would look like this:
|
||
+So if we try to match `"the 3 pigs"` from position 4, our progress through the flow chart would look like this:
|
||
|
||
* At position 4, there is a word boundary, so we can move past the first box.
|
||
|
||
@@ -300,17 +300,15 @@ So if we try to match `"the 3 pigs"` with our regular expression, our progress t
|
||
|
||
* We're at position 10 (the end of the string) and can match only a word boundary. The end of a string counts as a word boundary, so we go through the last box and have successfully matched this string.
|
||
|
||
-Conceptually, a regular expression engine looks for a match in a string as follows: it starts at the start of the string and tries a match there. In this case, there _is_ a word boundary there, so it'd get past the first box—but there is no digit, so it'd fail at the second box. Then it moves on to the second character in the string and tries to begin a new match there... and so on, until it finds a match or reaches the end of the string and decides that there really is no match.
|
||
-
|
||
## Backtracking
|
||
|
||
-The regular expression `/\b([01]+b|\d+|[\da-f]+h)\b/` matches either a binary number followed by a _b_, a regular decimal number with no suffix character, or a hexadecimal number (that is, base 16, with the letters _a_ to _f_ standing for the digits 10 to 15) followed by an _h_. This is the corresponding diagram:
|
||
+The regular expression `/<wbr>\b([01]+b|[\da-f]+h|\d+)\b/<wbr>` matches either a binary number followed by a _b_, a hexadecimal number (that is, base 16, with the letters _a_ to _f_ standing for the digits 10 to 15) followed by an _h_, or a regular decimal number with no suffix character. This is the corresponding diagram:
|
||
|
||
-![Visualization of /\b([01]+b|\d+|[\da-f]+h)\b/](img/re_number.svg)
|
||
+<figure>![Visualization of /\b([01]+b|\d+|[\da-f]+h)\b/](img/re_number.svg)</figure>
|
||
|
||
When matching this expression, it will often happen that the top (binary) branch is entered even though the input does not actually contain a binary number. When matching the string `"103"`, for example, it becomes clear only at the 3 that we are in the wrong branch. The string _does_ match the expression, just not the branch we are currently in.
|
||
|
||
-So the matcher _backtracks_. When entering a branch, it remembers its current position (in this case, at the start of the string, just past the first boundary box in the diagram) so that it can go back and try another branch if the current one does not work out. For the string `"103"`, after encountering the 3 character, it will start trying the branch for decimal numbers. This one matches, so a match is reported after all.
|
||
+So the matcher _backtracks_. When entering a branch, it remembers its current position (in this case, at the start of the string, just past the first boundary box in the diagram) so that it can go back and try another branch if the current one does not work out. For the string `"103"`, after encountering the 3 character, it will start trying the branch for hexadecimal numbers, which fails again because there is no _h_ after the number. So it tries the decimal number branch. This one fits, and a match is reported after all.
|
||
|
||
The matcher stops as soon as it finds a full match. This means that if multiple branches could potentially match a string, only the first one (ordered by where the branches appear in the regular expression) is used.
|
||
|
||
@@ -318,13 +316,13 @@ Backtracking also happens for repetition operators like + and `*`. If you match
|
||
|
||
It is possible to write regular expressions that will do a _lot_ of backtracking. This problem occurs when a pattern can match a piece of input in many different ways. For example, if we get confused while writing a binary-number regular expression, we might accidentally write something like `/([01]+)+b/`.
|
||
|
||
-![Visualization of /([01]+)+b/](img/re_slow.svg)
|
||
+<figure>![Visualization of /([01]+)+b/](img/re_slow.svg)</figure>
|
||
|
||
-If that tries to match some long series of zeros and ones with no trailing _b_ character, the matcher will first go through the inner loop until it runs out of digits. Then it notices there is no _b_, so it backtracks one position, goes through the outer loop once, and gives up again, trying to backtrack out of the inner loop once more. It will continue to try every possible route through these two loops. This means the amount of work _doubles_ with each additional character. For even just a few dozen characters, the resulting match will take practically forever.
|
||
+If that tries to match some long series of zeros and ones with no trailing _b_ character, the matcher first goes through the inner loop until it runs out of digits. Then it notices there is no _b_, so it backtracks one position, goes through the outer loop once, and gives up again, trying to backtrack out of the inner loop once more. It will continue to try every possible route through these two loops. This means the amount of work _doubles_ with each additional character. For even just a few dozen characters, the resulting match will take practically forever.
|
||
|
||
## The replace method
|
||
|
||
-String values have a `replace` method, which can be used to replace part of the string with another string.
|
||
+String values have a `replace` method that can be used to replace part of the string with another string.
|
||
|
||
```
|
||
console.log("papa".replace("p", "m"));
|
||
@@ -342,41 +340,41 @@ console.log("Borobudur".replace(/[ou]/g, "a"));
|
||
|
||
It would have been sensible if the choice between replacing one match or all matches was made through an additional argument to `replace` or by providing a different method, `replaceAll`. But for some unfortunate reason, the choice relies on a property of the regular expression instead.
|
||
|
||
-The real power of using regular expressions with `replace` comes from the fact that we can refer back to matched groups in the replacement string. For example, say we have a big string containing the names of people, one name per line, in the format `Lastname, Firstname`. If we want to swap these names and remove the comma to get a simple `Firstname Lastname` format, we can use the following code:
|
||
+The real power of using regular expressions with `replace` comes from the fact that we can refer back to matched groups in the replacement string. For example, say we have a big string containing the names of people, one name per line, in the format `Lastname, Firstname`. If we want to swap these names and remove the comma to get a `Firstname Lastname` format, we can use the following code:
|
||
|
||
```
|
||
console.log(
|
||
- "Hopper, Grace\nMcCarthy, John\nRitchie, Dennis"
|
||
- .replace(/([\w ]+), ([\w ]+)/g, "$2 $1"));
|
||
-// → Grace Hopper
|
||
+ "Liskov, Barbara\nMcCarthy, John\nWadler, Philip"
|
||
+ .replace(/(\w+), (\w+)/g, "$2 $1"));
|
||
+// → Barbara Liskov
|
||
// John McCarthy
|
||
-// Dennis Ritchie
|
||
+// Philip Wadler
|
||
```
|
||
|
||
The `$1` and `$2` in the replacement string refer to the parenthesized groups in the pattern. `$1` is replaced by the text that matched against the first group, `$2` by the second, and so on, up to `$9`. The whole match can be referred to with `><`.
|
||
|
||
-It is also possible to pass a function, rather than a string, as the second argument to `replace`. For each replacement, the function will be called with the matched groups (as well as the whole match) as arguments, and its return value will be inserted into the new string.
|
||
+It is possible to pass a function—rather than a string—as the second argument to `replace`. For each replacement, the function will be called with the matched groups (as well as the whole match) as arguments, and its return value will be inserted into the new string.
|
||
|
||
-Here's a simple example:
|
||
+Here's a small example:
|
||
|
||
```
|
||
-var s = "the cia and fbi";
|
||
-console.log(s.replace(/\b(fbi|cia)\b/g, function(str) {
|
||
- return str.toUpperCase();
|
||
-}));
|
||
+let s = "the cia and fbi";
|
||
+console.log(s.replace(/\b(fbi|cia)\b/g,
|
||
+ str => str.toUpperCase()));
|
||
// → the CIA and FBI
|
||
```
|
||
|
||
And here's a more interesting one:
|
||
|
||
```
|
||
-var stock = "1 lemon, 2 cabbages, and 101 eggs";
|
||
+let stock = "1 lemon, 2 cabbages, and 101 eggs";
|
||
function minusOne(match, amount, unit) {
|
||
amount = Number(amount) - 1;
|
||
- if (amount == 1) // only one left, remove the 's'
|
||
+ if (amount == 1) { // only one left, remove the 's'
|
||
unit = unit.slice(0, unit.length - 1);
|
||
- else if (amount == 0)
|
||
+ } else if (amount == 0) {
|
||
amount = "no";
|
||
+ }
|
||
return amount + " " + unit;
|
||
}
|
||
console.log(stock.replace(/(\d+) (\w+)/g, minusOne));
|
||
@@ -389,7 +387,7 @@ The `(\d+)` group ends up as the `amount` argument to the function, and the `(\w
|
||
|
||
## Greed
|
||
|
||
-It isn't hard to use `replace` to write a function that removes all comments from a piece of JavaScript code. Here is a first attempt:
|
||
+It is possible to use `replace` to write a function that removes all comments from a piece of JavaScript code. Here is a first attempt:
|
||
|
||
```
|
||
function stripComments(code) {
|
||
@@ -403,9 +401,9 @@ console.log(stripComments("1 /* a */+/* b */ 1"));
|
||
// → 1 1
|
||
```
|
||
|
||
-The part before the _or_ operator simply matches two slash characters followed by any number of non-newline characters. The part for multiline comments is more involved. We use `[^]` (any character that is not in the empty set of characters) as a way to match any character. We cannot just use a dot here because block comments can continue on a new line, and dots do not match the newline character.
|
||
+The part before the _or_ operator matches two slash characters followed by any number of non-newline characters. The part for multiline comments is more involved. We use `[^]` (any character that is not in the empty set of characters) as a way to match any character. We cannot just use a period here because block comments can continue on a new line, and the period character does not match newline characters.
|
||
|
||
-But the output of the previous example appears to have gone wrong. Why?
|
||
+But the output for the last line appears to have gone wrong. Why?
|
||
|
||
The `[^]*` part of the expression, as I described in the section on backtracking, will first match as much as it can. If that causes the next part of the pattern to fail, the matcher moves back one character and tries again from there. In the example, the matcher first tries to match the whole rest of the string and then moves back from there. It will find an occurrence of `*/` after going back four characters and match that. This is not what we wanted—the intention was to match a single comment, not to go all the way to the end of the code and find the end of the last block comment.
|
||
|
||
@@ -430,31 +428,31 @@ There are cases where you might not know the exact pattern you need to match aga
|
||
But you can build up a string and use the `RegExp` constructor on that. Here's an example:
|
||
|
||
```
|
||
-var name = "harry";
|
||
-var text = "Harry is a suspicious character.";
|
||
-var regexp = new RegExp("\\b(" + name + ")\\b", "gi");
|
||
+let name = "harry";
|
||
+let text = "Harry is a suspicious character.";
|
||
+let regexp = new RegExp("\\b(" + name + ")\\b", "gi");
|
||
console.log(text.replace(regexp, "_$1_"));
|
||
// → _Harry_ is a suspicious character.
|
||
```
|
||
|
||
-When creating the `\b` boundary markers, we have to use two backslashes because we are writing them in a normal string, not a slash-enclosed regular expression. The second argument to the `RegExp` constructor contains the options for the regular expression—in this case `"gi"` for global and case-insensitive.
|
||
+When creating the `\b` boundary markers, we have to use two backslashes because we are writing them in a normal string, not a slash-enclosed regular expression. The second argument to the `RegExp` constructor contains the options for the regular expression—in this case, `"gi"` for global and case-insensitive.
|
||
|
||
-But what if the name is `"dea+hl[]rd"` because our user is a nerdy teenager? That would result in a nonsensical regular expression, which won't actually match the user's name.
|
||
+But what if the name is `"dea+hl[]rd"` because our user is a nerdy teenager? That would result in a nonsensical regular expression that won't actually match the user's name.
|
||
|
||
-To work around this, we can add backslashes before any character that we don't trust. Adding backslashes before alphabetic characters is a bad idea because things like `\b` and `\n` have a special meaning. But escaping everything that's not alphanumeric or whitespace is safe.
|
||
+To work around this, we can add backslashes before any character that has a special meaning.
|
||
|
||
```
|
||
-var name = "dea+hl[]rd";
|
||
-var text = "This dea+hl[]rd guy is super annoying.";
|
||
-var escaped = name.replace(/[^\w\s]/g, "\\><");
|
||
-var regexp = new RegExp("\\b(" + escaped + ")\\b", "gi");
|
||
-console.log(text.replace(regexp, "_$1_"));
|
||
+let name = "dea+hl[]rd";
|
||
+let text = "This dea+hl[]rd guy is super annoying.";
|
||
+let escaped = name.replace(/[\\[.+*?(){|^$]/g, "\\><");
|
||
+let regexp = new RegExp("\\b" + escaped + "\\b", "gi");
|
||
+console.log(text.replace(regexp, "_><_"));
|
||
// → This _dea+hl[]rd_ guy is super annoying.
|
||
```
|
||
|
||
## The search method
|
||
|
||
-The `indexOf` method on strings cannot be called with a regular expression. But there is another method, `search`, which does expect a regular expression. Like `indexOf`, it returns the first index on which the expression was found, or -1 when it wasn't found.
|
||
+The `indexOf` method on strings cannot be called with a regular expression. But there is another method, `search`, that does expect a regular expression. Like `indexOf`, it returns the first index on which the expression was found, or -1 when it wasn't found.
|
||
|
||
```
|
||
console.log(" word".search(/\S/));
|
||
@@ -471,12 +469,12 @@ The `exec` method similarly does not provide a convenient way to start searching
|
||
|
||
Regular expression objects have properties. One such property is `source`, which contains the string that expression was created from. Another property is `lastIndex`, which controls, in some limited circumstances, where the next match will start.
|
||
|
||
-Those circumstances are that the regular expression must have the global (`g`) option enabled, and the match must happen through the `exec` method. Again, a more sane solution would have been to just allow an extra argument to be passed to `exec`, but sanity is not a defining characteristic of JavaScript's regular expression interface.
|
||
+Those circumstances are that the regular expression must have the global (`g`) or sticky (`y`) option enabled, and the match must happen through the `exec` method. Again, a less confusing solution would have been to just allow an extra argument to be passed to `exec`, but confusion is an essential feature of JavaScript's regular expression interface.
|
||
|
||
```
|
||
-var pattern = /y/g;
|
||
+let pattern = /y/g;
|
||
pattern.lastIndex = 3;
|
||
-var match = pattern.exec("xyzzy");
|
||
+let match = pattern.exec("xyzzy");
|
||
console.log(match.index);
|
||
// → 4
|
||
console.log(pattern.lastIndex);
|
||
@@ -485,10 +483,21 @@ console.log(pattern.lastIndex);
|
||
|
||
If the match was successful, the call to `exec` automatically updates the `lastIndex` property to point after the match. If no match was found, `lastIndex` is set back to zero, which is also the value it has in a newly constructed regular expression object.
|
||
|
||
-When using a global regular expression value for multiple `exec` calls, these automatic updates to the `lastIndex` property can cause problems. Your regular expression might be accidentally starting at an index that was left over from a previous call.
|
||
+The difference between the global and the sticky options is that, when sticky is enabled, the match will only succeed if it starts directly at `lastIndex`, whereas with global, it will search ahead for a position where a match can start.
|
||
|
||
```
|
||
-var digit = /\d/g;
|
||
+let global = /abc/g;
|
||
+console.log(global.exec("xyz abc"));
|
||
+// → ["abc"]
|
||
+let sticky = /abc/y;
|
||
+console.log(sticky.exec("xyz abc"));
|
||
+// → null
|
||
+```
|
||
+
|
||
+When using a shared regular expression value for multiple `exec` calls, these automatic updates to the `lastIndex` property can cause problems. Your regular expression might be accidentally starting at an index that was left over from a previous call.
|
||
+
|
||
+```
|
||
+let digit = /\d/g;
|
||
console.log(digit.exec("here it is: 1"));
|
||
// → ["1"]
|
||
console.log(digit.exec("and now: 1"));
|
||
@@ -506,27 +515,28 @@ So be cautious with global regular expressions. The cases where they are necessa
|
||
|
||
### Looping over matches
|
||
|
||
-A common pattern is to scan through all occurrences of a pattern in a string, in a way that gives us access to the match object in the loop body, by using `lastIndex` and `exec`.
|
||
+A common thing to do is to scan through all occurrences of a pattern in a string, in a way that gives us access to the match object in the loop body. We can do this by using `lastIndex` and `exec`.
|
||
|
||
```
|
||
-var input = "A string with 3 numbers in it... 42 and 88.";
|
||
-var number = /\b(\d+)\b/g;
|
||
-var match;
|
||
-while (match = number.exec(input))
|
||
- console.log("Found", match[1], "at", match.index);
|
||
+let input = "A string with 3 numbers in it... 42 and 88.";
|
||
+let number = /\b\d+\b/g;
|
||
+let match;
|
||
+while (match = number.exec(input)) {
|
||
+ console.log("Found", match[0], "at", match.index);
|
||
+}
|
||
// → Found 3 at 14
|
||
// Found 42 at 33
|
||
// Found 88 at 40
|
||
```
|
||
|
||
-This makes use of the fact that the value of an assignment expression (`=`) is the assigned value. So by using `match = number.exec(input)` as the condition in the `while` statement, we perform the match at the start of each iteration, save its result in a variable, and stop looping when no more matches are found.
|
||
+This makes use of the fact that the value of an assignment expression (`=`) is the assigned value. So by using `match = number.<wbr>exec(input)` as the condition in the `while` statement, we perform the match at the start of each iteration, save its result in a binding, and stop looping when no more matches are found.
|
||
|
||
## Parsing an INI file
|
||
|
||
-To conclude the chapter, we'll look at a problem that calls for regular expressions. Imagine we are writing a program to automatically harvest information about our enemies from the Internet. (We will not actually write that program here, just the part that reads the configuration file. Sorry to disappoint.) The configuration file looks like this:
|
||
+To conclude the chapter, we'll look at a problem that calls for regular expressions. Imagine we are writing a program to automatically collect information about our enemies from the Internet. (We will not actually write that program here, just the part that reads the configuration file. Sorry.) The configuration file looks like this:
|
||
|
||
```
|
||
-searchengine=http://www.google.com/search?q=$1
|
||
+searchengine=https://duckduckgo.com/?q=$1
|
||
spitefulness=9.7
|
||
|
||
; comments are preceded by a semicolon...
|
||
@@ -536,13 +546,13 @@ fullname=Larry Doe
|
||
type=kindergarten bully
|
||
website=http://www.geocities.com/CapeCanaveral/11451
|
||
|
||
-[gargamel]
|
||
-fullname=Gargamel
|
||
-type=evil sorcerer
|
||
-outputdir=/home/marijn/enemies/gargamel
|
||
+[davaeorn]
|
||
+fullname=Davaeorn
|
||
+type=evil wizard
|
||
+outputdir=/home/marijn/enemies/davaeorn
|
||
```
|
||
|
||
-The exact rules for this format (which is actually a widely used format, usually called an _INI_ file) are as follows:
|
||
+The exact rules for this format (which is a widely used format, usually called an _INI_ file) are as follows:
|
||
|
||
* Blank lines and lines starting with semicolons are ignored.
|
||
|
||
@@ -552,58 +562,84 @@ The exact rules for this format (which is actually a widely used format, usually
|
||
|
||
* Anything else is invalid.
|
||
|
||
-Our task is to convert a string like this into an array of objects, each with a `name` property and an array of settings. We'll need one such object for each section and one for the global settings at the top.
|
||
+Our task is to convert a string like this into an object whose properties hold strings for sectionless settings and sub-objects for sections, with those sub-objects holding the section's settings.
|
||
|
||
-Since the format has to be processed line by line, splitting up the file into separate lines is a good start. We used `string.split("\n")` to do this in [Chapter 6](06_object.html#split). Some operating systems, however, use not just a newline character to separate lines but a carriage return character followed by a newline (`"\r\n"`). Given that the `split` method also allows a regular expression as its argument, we can split on a regular expression like `/\r?\n/` to split in a way that allows both `"\n"` and `"\r\n"` between lines.
|
||
+Since the format has to be processed line by line, splitting up the file into separate lines is a good start. We used `string.<wbr>split("\n")` to do this in [Chapter 4](04_data.html#split). Some operating systems, however, use not just a newline character to separate lines but a carriage return character followed by a newline (`"\r\n"`). Given that the `split` method also allows a regular expression as its argument, we can use a regular expression like `/\r?\n/` to split in a way that allows both `"\n"` and `"\r\n"` between lines.
|
||
|
||
```
|
||
function parseINI(string) {
|
||
// Start with an object to hold the top-level fields
|
||
- var currentSection = {name: null, fields: []};
|
||
- var categories = [currentSection];
|
||
-
|
||
- string.split(/\r?\n/).forEach(function(line) {
|
||
- var match;
|
||
- if (/^\s*(;.*)?$/.test(line)) {
|
||
- return;
|
||
+ let result = {};
|
||
+ let section = result;
|
||
+ string.split(/\r?\n/).forEach(line => {
|
||
+ let match;
|
||
+ if (match = line.match(/^(\w+)=(.*)$/)) {
|
||
+ section[match[1]] = match[2];
|
||
} else if (match = line.match(/^\[(.*)\]$/)) {
|
||
- currentSection = {name: match[1], fields: []};
|
||
- categories.push(currentSection);
|
||
- } else if (match = line.match(/^(\w+)=(.*)$/)) {
|
||
- currentSection.fields.push({name: match[1],
|
||
- value: match[2]});
|
||
- } else {
|
||
- throw new Error("Line '" + line + "' is invalid.");
|
||
+ section = result[match[1]] = {};
|
||
+ } else if (!/^\s*(;.*)?$/.test(line)) {
|
||
+ throw new Error("Line '" + line + "' is not valid.");
|
||
}
|
||
});
|
||
-
|
||
- return categories;
|
||
+ return result;
|
||
}
|
||
-```
|
||
|
||
-This code goes over every line in the file, updating the “current section” object as it goes along. First, it checks whether the line can be ignored, using the expression `/^\s*(;.*)?$/`. Do you see how it works? The part between the parentheses will match comments, and the `?` will make sure it also matches lines containing only whitespace.
|
||
-
|
||
-If the line is not a comment, the code then checks whether the line starts a new section. If so, it creates a new current section object, to which subsequent settings will be added.
|
||
+console.log(parseINI(`
|
||
+name=Vasilis
|
||
+[address]
|
||
+city=Tessaloniki`));
|
||
+// → {name: "Vasilis", address: {city: "Tessaloniki"}}
|
||
+```
|
||
|
||
-The last meaningful possibility is that the line is a normal setting, which the code adds to the current section object.
|
||
+The code goes over the file's lines and builds up an object. Properties at the top are stored directly into that object, whereas properties found in sections are stored in a separate section object. The `section` binding points at the object for the current section.
|
||
|
||
-If a line matches none of these forms, the function throws an error.
|
||
+There are two kinds of significant lines—section headers or property lines. When a line is a regular property, it is stored in the current section. When it is a section header, a new section object is created, and `section` is set to point at it.
|
||
|
||
Note the recurring use of `^` and `<article to make sure the expression matches the whole line, not just part of it. Leaving these out results in code that mostly works but behaves strangely for some input, which can be a difficult bug to track down.
|
||
|
||
-The pattern `if (match = string.match(...))` is similar to the trick of using an assignment as the condition for `while`. You often aren't sure that your call to `match` will succeed, so you can access the resulting object only inside an `if` statement that tests for this. To not break the pleasant chain of `if` forms, we assign the result of the match to a variable and immediately use that assignment as the test in the `if` statement.
|
||
+The pattern `if (match = string.<wbr>match(.<wbr>.<wbr>.<wbr>))` is similar to the trick of using an assignment as the condition for `while`. You often aren't sure that your call to `match` will succeed, so you can access the resulting object only inside an `if` statement that tests for this. To not break the pleasant chain of `else if` forms, we assign the result of the match to a binding and immediately use that assignment as the test for the `if` statement.
|
||
+
|
||
+If a line is not a section header or a property, the function checks whether it is a comment or an empty line using the expression `/^\s*(;.*)?$/`. Do you see how it works? The part between the parentheses will match comments, and the `?` makes sure it also matches lines containing only whitespace. When a line doesn't match any of the expected forms, the function throws an exception.
|
||
|
||
## International characters
|
||
|
||
-Because of JavaScript's initial simplistic implementation and the fact that this simplistic approach was later set in stone as standard behavior, JavaScript's regular expressions are rather dumb about characters that do not appear in the English language. For example, as far as JavaScript's regular expressions are concerned, a “word character” is only one of the 26 characters in the Latin alphabet (uppercase or lowercase) and, for some reason, the underscore character. Things like _é_ or _β_, which most definitely are word characters, will not match `\w` (and _will_ match uppercase `\W`, the nonword category).
|
||
+Because of JavaScript's initial simplistic implementation and the fact that this simplistic approach was later set in stone as standard behavior, JavaScript's regular expressions are rather dumb about characters that do not appear in the English language. For example, as far as JavaScript's regular expressions are concerned, a “word character” is only one of the 26 characters in the Latin alphabet (uppercase or lowercase), decimal digits, and, for some reason, the underscore character. Things like _é_ or _β_, which most definitely are word characters, will not match `\w` (and _will_ match uppercase `\W`, the nonword category).
|
||
|
||
By a strange historical accident, `\s` (whitespace) does not have this problem and matches all characters that the Unicode standard considers whitespace, including things like the nonbreaking space and the Mongolian vowel separator.
|
||
|
||
-Some regular expression implementations in other programming languages have syntax to match specific Unicode character categories, such as “all uppercase letters”, “all punctuation”, or “control characters”. There are plans to add support for such categories to JavaScript, but it unfortunately looks like they won't be realized in the near future.
|
||
+Another problem is that, by default, regular expressions work on code units, as discussed in [Chapter 5](05_higher_order.html#code_units), not actual characters. This means that characters that are composed of two code units behave strangely.
|
||
+
|
||
+```
|
||
+console.log(/🍎{3}/.test("🍎🍎🍎"));
|
||
+// → false
|
||
+console.log(/<.>/.test("<🌹>"));
|
||
+// → false
|
||
+console.log(/<.>/u.test("<🌹>"));
|
||
+// → true
|
||
+```
|
||
+
|
||
+The problem is that the 🍎 in the first line is treated as two code units, and the `{3}` part is applied only to the second one. Similarly, the dot matches a single code unit, not the two that make up the rose emoji.
|
||
+
|
||
+You must add a `u` option (for Unicode) to your regular expression to make it treat such characters properly. The wrong behavior remains the default, unfortunately, because changing that might cause problems for existing code that depends on it.
|
||
+
|
||
+Though this was only just standardized and is, at the time of writing, not widely supported yet, it is possible to use `\p` in a regular expression (that must have the Unicode option enabled) to match all characters to which the Unicode standard assigns a given property.
|
||
+
|
||
+```
|
||
+console.log(/\p{Script=Greek}/u.test("α"));
|
||
+// → true
|
||
+console.log(/\p{Script=Arabic}/u.test("α"));
|
||
+// → false
|
||
+console.log(/\p{Alphabetic}/u.test("α"));
|
||
+// → true
|
||
+console.log(/\p{Alphabetic}/u.test("!"));
|
||
+// → false
|
||
+```
|
||
+
|
||
+Unicode defines a number of useful properties, though finding the one that you need may not always be trivial. You can use the `\p{Property=Value}` notation to match any character that has the given value for that property. If the property name is left off, as in `\p{Name}`, the name is assumed to either be a binary property such as `Alphabetic` or a category such as `Number`.
|
||
|
||
## Summary
|
||
|
||
-Regular expressions are objects that represent patterns in strings. They use their own syntax to express these patterns.
|
||
+Regular expressions are objects that represent patterns in strings. They use their own language to express these patterns.
|
||
|
||
| `/abc/` | A sequence of characters |
|
||
| `/[abc]/` | Any character from a set of characters |
|
||
@@ -613,7 +649,7 @@ Regular expressions are objects that represent patterns in strings. They use the
|
||
| `/x+?/` | One or more occurrences, nongreedy |
|
||
| `/x*/` | Zero or more occurrences |
|
||
| `/x?/` | Zero or one occurrence |
|
||
-| `/x{2,4}/` | Between two and four occurrences |
|
||
+| `/x{2,4}/` | Two to four occurrences |
|
||
| `/(abc)/` | A group |
|
||
| `/a|b|c/` | Any one of several patterns |
|
||
| `/\d/` | Any digit character |
|
||
@@ -624,15 +660,13 @@ Regular expressions are objects that represent patterns in strings. They use the
|
||
| `/^/` | Start of input |
|
||
| `/$/` | End of input |
|
||
|
||
-A regular expression has a method `test` to test whether a given string matches it. It also has an `exec` method that, when a match is found, returns an array containing all matched groups. Such an array has an `index` property that indicates where the match started.
|
||
-
|
||
-Strings have a `match` method to match them against a regular expression and a `search` method to search for one, returning only the starting position of the match. Their `replace` method can replace matches of a pattern with a replacement string. Alternatively, you can pass a function to `replace`, which will be used to build up a replacement string based on the match text and matched groups.
|
||
+A regular expression has a method `test` to test whether a given string matches it. It also has a method `exec` that, when a match is found, returns an array containing all matched groups. Such an array has an `index` property that indicates where the match started.
|
||
|
||
-Regular expressions can have options, which are written after the closing slash. The `i` option makes the match case insensitive, while the `g` option makes the expression _global_, which, among other things, causes the `replace` method to replace all instances instead of just the first.
|
||
+Strings have a `match` method to match them against a regular expression and a `search` method to search for one, returning only the starting position of the match. Their `replace` method can replace matches of a pattern with a replacement string or function.
|
||
|
||
-The `RegExp` constructor can be used to create a regular expression value from a string.
|
||
+Regular expressions can have options, which are written after the closing slash. The `i` option makes the match case-insensitive. The `g` option makes the expression _global_, which, among other things, causes the `replace` method to replace all instances instead of just the first. The `y` option makes it sticky, which means that it will not search ahead and skip part of the string when looking for a match. The `u` option turns on Unicode mode, which fixes a number of problems around the handling of characters that take up two code units.
|
||
|
||
-Regular expressions are a sharp tool with an awkward handle. They simplify some tasks tremendously but can quickly become unmanageable when applied to complex problems. Part of knowing how to use them is resisting the urge to try to shoehorn things that they cannot sanely express into them.
|
||
+Regular expressions are a sharp tool with an awkward handle. They simplify some tasks tremendously but can quickly become unmanageable when applied to complex problems. Part of knowing how to use them is resisting the urge to try to shoehorn things that they cannot cleanly express into them.
|
||
|
||
## Exercises
|
||
|
||
@@ -652,11 +686,11 @@ For each of the following items, write a regular expression to test whether any
|
||
|
||
4. Any word ending in _ious_
|
||
|
||
-5. A whitespace character followed by a dot, comma, colon, or semicolon
|
||
+5. A whitespace character followed by a period, comma, colon, or semicolon
|
||
|
||
6. A word longer than six letters
|
||
|
||
-7. A word without the letter _e_
|
||
+7. A word without the letter _e_ (or _E_)
|
||
|
||
Refer to the table in the [chapter summary](09_regexp.html#summary_regexp) for help. Test each solution with a few test strings.
|
||
|
||
@@ -669,7 +703,7 @@ verify(/.../,
|
||
|
||
verify(/.../,
|
||
["pop culture", "mad props"],
|
||
- ["plop"]);
|
||
+ ["plop", "prrrop"]);
|
||
|
||
verify(/.../,
|
||
["ferret", "ferry", "ferrari"],
|
||
@@ -681,7 +715,7 @@ verify(/.../,
|
||
|
||
verify(/.../,
|
||
["bad punctuation ."],
|
||
- ["escape the dot"]);
|
||
+ ["escape the period"]);
|
||
|
||
verify(/.../,
|
||
["hottentottententen"],
|
||
@@ -689,19 +723,17 @@ verify(/.../,
|
||
|
||
verify(/.../,
|
||
["red platypus", "wobbling nest"],
|
||
- ["earth bed", "learning ape"]);
|
||
+ ["earth bed", "learning ape", "BEET"]);
|
||
|
||
function verify(regexp, yes, no) {
|
||
// Ignore unfinished exercises
|
||
if (regexp.source == "...") return;
|
||
- yes.forEach(function(s) {
|
||
- if (!regexp.test(s))
|
||
- console.log("Failure to match '" + s + "'");
|
||
- });
|
||
- no.forEach(function(s) {
|
||
- if (regexp.test(s))
|
||
- console.log("Unexpected match for '" + s + "'");
|
||
- });
|
||
+ for (let str of yes) if (!regexp.test(str)) {
|
||
+ console.log(`Failure to match '${str}'`);
|
||
+ }
|
||
+ for (let str of no) if (regexp.test(str)) {
|
||
+ console.log(`Unexpected match for '${str}'`);
|
||
+ }
|
||
}
|
||
```
|
||
|
||
@@ -712,7 +744,7 @@ Imagine you have written a story and used single quotation marks throughout to m
|
||
Think of a pattern that distinguishes these two kinds of quote usage and craft a call to the `replace` method that does the proper replacement.
|
||
|
||
```
|
||
-var text = "'I'm the cook,' he said, 'it's my job.'";
|
||
+let text = "'I'm the cook,' he said, 'it's my job.'";
|
||
// Change this call.
|
||
console.log(text.replace(/A/g, "B"));
|
||
// → "I'm the cook," he said, "it's my job."
|
||
@@ -724,28 +756,28 @@ In addition, you must ensure that the replacement also includes the characters t
|
||
|
||
### Numbers again
|
||
|
||
-A series of digits can be matched by the simple regular expression `/\d+/`.
|
||
-
|
||
Write an expression that matches only JavaScript-style numbers. It must support an optional minus _or_ plus sign in front of the number, the decimal dot, and exponent notation—`5e-3` or `1E10`— again with an optional sign in front of the exponent. Also note that it is not necessary for there to be digits in front of or after the dot, but the number cannot be a dot alone. That is, `.5` and `5.` are valid JavaScript numbers, but a lone dot _isn't_.
|
||
|
||
```
|
||
// Fill in this regular expression.
|
||
-var number = /^...$/;
|
||
+let number = /^...$/;
|
||
|
||
// Tests:
|
||
-["1", "-1", "+15", "1.55", ".5", "5.", "1.3e2", "1E-4",
|
||
- "1e+12"].forEach(function(s) {
|
||
- if (!number.test(s))
|
||
- console.log("Failed to match '" + s + "'");
|
||
-});
|
||
-["1a", "+-1", "1.2.3", "1+1", "1e4.5", ".5.", "1f5",
|
||
- "."].forEach(function(s) {
|
||
- if (number.test(s))
|
||
- console.log("Incorrectly accepted '" + s + "'");
|
||
-});
|
||
-```
|
||
-
|
||
-First, do not forget the backslash in front of the dot.
|
||
+for (let str of ["1", "-1", "+15", "1.55", ".5", "5.",
|
||
+ "1.3e2", "1E-4", "1e+12"]) {
|
||
+ if (!number.test(str)) {
|
||
+ console.log(`Failed to match '${str}'`);
|
||
+ }
|
||
+}
|
||
+for (let str of ["1a", "+-1", "1.2.3", "1+1", "1e4.5",
|
||
+ ".5.", "1f5", "."]) {
|
||
+ if (number.test(str)) {
|
||
+ console.log(`Incorrectly accepted '${str}'`);
|
||
+ }
|
||
+}
|
||
+```
|
||
+
|
||
+First, do not forget the backslash in front of the period.
|
||
|
||
Matching the optional sign in front of the number, as well as in front of the exponent, can be done with `[+\-]?` or `(\+|-|)` (plus, minus, or nothing).
|
||
|