up
This commit is contained in:
parent
ab9ab64bd5
commit
97c8f22bbb
289 changed files with 195 additions and 172 deletions
|
@ -0,0 +1,29 @@
|
|||
A regexp to search 3-digit color `#abc`: `pattern:/#[a-f0-9]{3}/i`.
|
||||
|
||||
We can add exactly 3 more optional hex digits. We don't need more or less. Either we have them or we don't.
|
||||
|
||||
The simplest way to add them -- is to append to the regexp: `pattern:/#[a-f0-9]{3}([a-f0-9]{3})?/i`
|
||||
|
||||
We can do it in a smarter way though: `pattern:/#([a-f0-9]{3}){1,2}/i`.
|
||||
|
||||
Here the regexp `pattern:[a-f0-9]{3}` is in parentheses to apply the quantifier `pattern:{1,2}` to it as a whole.
|
||||
|
||||
In action:
|
||||
|
||||
```js run
|
||||
let reg = /#([a-f0-9]{3}){1,2}/gi;
|
||||
|
||||
let str = "color: #3f3; background-color: #AA00ef; and: #abcd";
|
||||
|
||||
alert( str.match(reg) ); // #3f3 #AA0ef #abc
|
||||
```
|
||||
|
||||
There's minor problem here: the pattern found `match:#abc` in `subject:#abcd`. To prevent that we can add `pattern:\b` to the end:
|
||||
|
||||
```js run
|
||||
let reg = /#([a-f0-9]{3}){1,2}\b/gi;
|
||||
|
||||
let str = "color: #3f3; background-color: #AA00ef; and: #abcd";
|
||||
|
||||
alert( str.match(reg) ); // #3f3 #AA0ef
|
||||
```
|
|
@ -0,0 +1,14 @@
|
|||
# Find color in the format #abc or #abcdef
|
||||
|
||||
Write a regexp that matches colors in the format `#abc` or `#abcdef`. That is: `#` followed by 3 or 6 hexadimal digits.
|
||||
|
||||
Usage example:
|
||||
```js
|
||||
let reg = /your regexp/g;
|
||||
|
||||
let str = "color: #3f3; background-color: #AA00ef; and: #abcd";
|
||||
|
||||
alert( str.match(reg) ); // #3f3 #AA0ef
|
||||
```
|
||||
|
||||
P.S. Should be exactly 3 or 6 hex digits: values like `#abcd` should not match.
|
|
@ -0,0 +1,16 @@
|
|||
|
||||
An integer number is `pattern:\d+`.
|
||||
|
||||
A decimal part is: `pattern:\.\d+`.
|
||||
|
||||
Because the decimal part is optional, let's put it in parentheses with quantifier `pattern:'?'`.
|
||||
|
||||
Finally we have the regexp: `pattern:\d+(\.\d+)?`:
|
||||
|
||||
```js run
|
||||
let reg = /\d+(\.\d+)?/g;
|
||||
|
||||
let str = "1.5 0 12. 123.4.";
|
||||
|
||||
alert( str.match(re) ); // 1.5, 0, 12, 123.4
|
||||
```
|
|
@ -0,0 +1,12 @@
|
|||
# Find positive numbers
|
||||
|
||||
Create a regexp that looks for positive numbers, including those without a decimal point.
|
||||
|
||||
An example of use:
|
||||
```js
|
||||
let reg = /your regexp/g;
|
||||
|
||||
let str = "1.5 0 12. 123.4.";
|
||||
|
||||
alert( str.match(reg) ); // 1.5, 0, 12, 123.4
|
||||
```
|
|
@ -0,0 +1,11 @@
|
|||
A positive number with an optional decimal part is (per previous task): `pattern:\d+(\.\d+)?`.
|
||||
|
||||
Let's add an optional `-` in the beginning:
|
||||
|
||||
```js run
|
||||
let reg = /-?\d+(\.\d+)?/g;
|
||||
|
||||
let str = "-1.5 0 2 -123.4.";
|
||||
|
||||
alert( str.match(reg) ); // -1.5, 0, 2, -123.4
|
||||
```
|
|
@ -0,0 +1,13 @@
|
|||
# Find all numbers
|
||||
|
||||
Write a regexp that looks for all decimal numbers including integer ones, with the floating point and negative ones.
|
||||
|
||||
An example of use:
|
||||
|
||||
```js
|
||||
let reg = /your regexp/g;
|
||||
|
||||
let str = "-1.5 0 2 -123.4.";
|
||||
|
||||
alert( str.match(re) ); // -1.5, 0, 2, -123.4
|
||||
```
|
|
@ -0,0 +1,49 @@
|
|||
A regexp for a number is: `pattern:-?\d+(\.\d+)?`. We created it in previous tasks.
|
||||
|
||||
An operator is `pattern:[-+*/]`. We put a dash `pattern:-` the first, because in the middle it would mean a character range, we don't need that.
|
||||
|
||||
Note that a slash should be escaped inside a JavaScript regexp `pattern:/.../`.
|
||||
|
||||
We need a number, an operator, and then another number. And optional spaces between them.
|
||||
|
||||
The full regular expression: `pattern:-?\d+(\.\d+)?\s*[-+*/]\s*-?\d+(\.\d+)?`.
|
||||
|
||||
To get a result as an array let's put parentheses around the data that we need: numbers and the operator: `pattern:(-?\d+(\.\d+)?)\s*([-+*/])\s*(-?\d+(\.\d+)?)`.
|
||||
|
||||
In action:
|
||||
|
||||
```js run
|
||||
let reg = /(-?\d+(\.\d+)?)\s*([-+*\/])\s*(-?\d+(\.\d+)?)/;
|
||||
|
||||
alert( "1.2 + 12".match(reg) );
|
||||
```
|
||||
|
||||
The result includes:
|
||||
|
||||
- `result[0] == "1.2 + 12"` (full match)
|
||||
- `result[1] == "1"` (first parentheses)
|
||||
- `result[2] == "2"` (second parentheses -- the decimal part `(\.\d+)?`)
|
||||
- `result[3] == "+"` (...)
|
||||
- `result[4] == "12"` (...)
|
||||
- `result[5] == undefined` (the last decimal part is absent, so it's undefined)
|
||||
|
||||
We need only numbers and the operator. We don't need decimal parts.
|
||||
|
||||
So let's remove extra groups from capturing by added `pattern:?:`, for instance: `pattern:(?:\.\d+)?`.
|
||||
|
||||
The final solution:
|
||||
|
||||
```js run
|
||||
function parse(expr) {
|
||||
let reg = /(-?\d+(?:\.\d+)?)\s*([-+*\/])\s*(-?\d+(?:\.\d+)?)/;
|
||||
|
||||
let result = expr.match(reg);
|
||||
|
||||
if (!result) return;
|
||||
result.shift();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
alert( parse("-1.23 * 3.45") ); // -1.23, *, 3.45
|
||||
```
|
|
@ -0,0 +1,28 @@
|
|||
# Parse an expression
|
||||
|
||||
An arithmetical expression consists of 2 numbers and an operator between them, for instance:
|
||||
|
||||
- `1 + 2`
|
||||
- `1.2 * 3.4`
|
||||
- `-3 / -6`
|
||||
- `-2 - 2`
|
||||
|
||||
The operator is one of: `"+"`, `"-"`, `"*"` or `"/"`.
|
||||
|
||||
There may be extra spaces at the beginning, at the end or between the parts.
|
||||
|
||||
Create a function `parse(expr)` that takes an expression and returns an array of 3 items:
|
||||
|
||||
1. The first number.
|
||||
2. The operator.
|
||||
3. The second number.
|
||||
|
||||
For example:
|
||||
|
||||
```js
|
||||
let [a, op, b] = parse("1.2 * 3.4");
|
||||
|
||||
alert(a); // 1.2
|
||||
alert(op); // *
|
||||
alert(b); // 3.4
|
||||
```
|
172
10-regular-expressions/09-regexp-groups/article.md
Normal file
172
10-regular-expressions/09-regexp-groups/article.md
Normal file
|
@ -0,0 +1,172 @@
|
|||
# Capturing groups
|
||||
|
||||
A part of the pattern can be enclosed in parentheses `pattern:(...)`. That's called a "capturing group".
|
||||
|
||||
That has two effects:
|
||||
|
||||
1. It allows to place a part of the match into a separate array item when using [String#match](mdn:js/String/match) or [RegExp#exec](mdn:/RegExp/exec) methods.
|
||||
2. If we put a quantifier after the parentheses, it applies to the parentheses as a whole, not the last character.
|
||||
|
||||
[cut]
|
||||
|
||||
## Example
|
||||
|
||||
In the example below the pattern `pattern:(go)+` finds one or more `match:'go'`:
|
||||
|
||||
```js run
|
||||
alert( 'Gogogo now!'.match(/(go)+/i) ); // "Gogogo"
|
||||
```
|
||||
|
||||
Without parentheses, the pattern `pattern:/go+/` means `subject:g`, followed by `subject:o` repeated one or more times. For instance, `match:goooo` or `match:gooooooooo`.
|
||||
|
||||
Parentheses group the word `pattern:(go)` together.
|
||||
|
||||
Let's make something more complex -- a regexp to match an email.
|
||||
|
||||
Examples of emails:
|
||||
|
||||
```
|
||||
my@mail.com
|
||||
john.smith@site.com.uk
|
||||
```
|
||||
|
||||
The pattern: `pattern:[-.\w]+@([\w-]+\.)+[\w-]{2,20}`.
|
||||
|
||||
- The first part before `@` may include wordly characters, a dot and a dash `pattern:[-.\w]+`, like `match:john.smith`.
|
||||
- Then `pattern:@`
|
||||
- And then the domain. May be a second-level domain `site.com` or with subdomains like `host.site.com.uk`. We can match it as "a word followed by a dot" repeated one or more times for subdomains: `match:mail.` or `match:site.com.`, and then "a word" for the last part: `match:.com` or `match:.uk`.
|
||||
|
||||
The word followed by a dot is `pattern:(\w+\.)+` (repeated). The last word should not have a dot at the end, so it's just `\w{2,20}`. The quantifier `pattern:{2,20}` limits the length, because domain zones are like `.uk` or `.com` or `.museum`, but can't be longer than 20 characters.
|
||||
|
||||
So the domain pattern is `pattern:(\w+\.)+\w{2,20}`. Now we replace `\w` with `[\w-]`, because dashes are also allowed in domains, and we get the final result.
|
||||
|
||||
That regexp is not perfect, but usually works. It's short and good enough to fix errors or occasional mistypes.
|
||||
|
||||
For instance, here we can find all emails in the string:
|
||||
|
||||
```js run
|
||||
let reg = /[-.\w]+@([\w-]+\.)+[\w-]{2,20}/g;
|
||||
|
||||
alert("my@mail.com @ his@site.com.uk".match(reg)); // my@mail.com,his@site.com.uk
|
||||
```
|
||||
|
||||
|
||||
## Contents of parentheses
|
||||
|
||||
Parentheses are numbered from left to right. The search engine remembers the content of each and allows to reference it in the pattern or in the replacement string.
|
||||
|
||||
For instance, we can find an HTML-tag using a (simplified) pattern `pattern:<.*?>`. Usually we'd want to do something with the result after it.
|
||||
|
||||
If we enclose the inner contents of `<...>` into parentheses, then we can access it like this:
|
||||
|
||||
```js run
|
||||
let str = '<h1>Hello, world!</h1>';
|
||||
let reg = /<(.*?)>/;
|
||||
|
||||
alert( str.match(reg) ); // Array: ["<h1>", "h1"]
|
||||
```
|
||||
|
||||
The call to [String#match](mdn:js/String/match) returns groups only if the regexp has no `pattern:/.../g` flag.
|
||||
|
||||
If we need all matches with their groups then we can use [RegExp#exec](mdn:js/RegExp/exec) method as described in <info:regexp-methods>:
|
||||
|
||||
```js run
|
||||
let str = '<h1>Hello, world!</h1>';
|
||||
|
||||
// two matches: opening <h1> and closing </h1> tags
|
||||
let reg = /<(.*?)>/g;
|
||||
|
||||
let match;
|
||||
|
||||
while (match = reg.exec(str)) {
|
||||
// first shows the match: <h1>,h1
|
||||
// then shows the match: </h1>,/h1
|
||||
alert(match);
|
||||
}
|
||||
```
|
||||
|
||||
Here we have two matches for `pattern:<(.*?)>`, each of them is an array with the full match and groups.
|
||||
|
||||
## Nested groups
|
||||
|
||||
Parentheses can be nested. In this case the numbering also goes from left to right.
|
||||
|
||||
For instance, when searching a tag in `subject:<span class="my">` we may be interested in:
|
||||
|
||||
1. The tag content as a whole: `match:span class="my"`.
|
||||
2. The tag name: `match:span`.
|
||||
3. The tag attributes: `match:class="my"`.
|
||||
|
||||
Let's add parentheses for them:
|
||||
|
||||
```js run
|
||||
let str = '<span class="my">';
|
||||
|
||||
let reg = /<(([a-z]+)\s*([^>]*))>/;
|
||||
|
||||
let result = str.match(reg);
|
||||
alert(result); // <span class="my">, span class="my", span, class="my"
|
||||
```
|
||||
|
||||
Here's how groups look:
|
||||
|
||||

|
||||
|
||||
At the zero index of the `result` is always the full match.
|
||||
|
||||
Then groups, numbered from left to right. Whichever opens first gives the first group `result[1]`. Here it encloses the whole tag content.
|
||||
|
||||
Then in `result[2]` goes the group from the second opening `pattern:(` till the corresponding `pattern:)` -- tag name, then we don't group spaces, but group attributes for `result[3]`.
|
||||
|
||||
**If a group is optional and doesn't exist in the match, the corresponding `result` index is present (and equals `undefined`).**
|
||||
|
||||
For instance, let's consider the regexp `pattern:a(z)?(c)?`. It looks for `"a"` optionally followed by `"z"` optionally followed by `"c"`.
|
||||
|
||||
If we run it on the string with a single letter `subject:a`, then the result is:
|
||||
|
||||
```js run
|
||||
let match = 'a'.match(/a(z)?(c)?/);
|
||||
|
||||
alert( match.length ); // 3
|
||||
alert( match[0] ); // a (whole match)
|
||||
alert( match[1] ); // undefined
|
||||
alert( match[2] ); // undefined
|
||||
```
|
||||
|
||||
The array has the length of `3`, but all groups are empty.
|
||||
|
||||
And here's a more complex match for the string `subject:ack`:
|
||||
|
||||
```js run
|
||||
let match = 'ack'.match(/a(z)?(c)?/)
|
||||
|
||||
alert( match.length ); // 3
|
||||
alert( match[0] ); // ac (whole match)
|
||||
alert( match[1] ); // undefined, because there's nothing for (z)?
|
||||
alert( match[2] ); // c
|
||||
```
|
||||
|
||||
The array length is permanent: `3`. But there's nothing for the group `pattern:(z)?`, so the result is `["ac", undefined, "c"]`.
|
||||
|
||||
## Non-capturing groups with ?:
|
||||
|
||||
Sometimes we need parentheses to correctly apply a quantifier, but we don't want their contents in the array.
|
||||
|
||||
A group may be excluded by adding `pattern:?:` in the beginning.
|
||||
|
||||
For instance, if we want to find `pattern:(go)+`, but don't want to put remember the contents (`go`) in a separate array item, we can write: `pattern:(?:go)+`.
|
||||
|
||||
In the example below we only get the name "John" as a separate member of the `results` array:
|
||||
|
||||
```js run
|
||||
let str = "Gogo John!";
|
||||
*!*
|
||||
// exclude Gogo from capturing
|
||||
let reg = /(?:go)+ (\w+)/i;
|
||||
*/!*
|
||||
|
||||
let result = str.match(reg);
|
||||
|
||||
alert( result.length ); // 2
|
||||
alert( result[1] ); // John
|
||||
```
|
BIN
10-regular-expressions/09-regexp-groups/regexp-nested-groups.png
Normal file
BIN
10-regular-expressions/09-regexp-groups/regexp-nested-groups.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 12 KiB |
Binary file not shown.
After Width: | Height: | Size: 25 KiB |
Loading…
Add table
Add a link
Reference in a new issue