You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Напишите регулярное выражение, которое находит цвет в формате `#abc`или`#abcdef`. То есть, символ `#`, после которого идут 3 или 6 шестнадцатиричных символа.
3
+
Write a regexp that matches colors in the format `#abc`or`#abcdef`. That is: `#` followed by 3 or 6 hexadimal digits.
4
4
5
-
Пример использования:
5
+
Usage example:
6
6
```js
7
-
var re=/* ваш регэксп */
7
+
let reg=/your regexp/g;
8
8
9
-
var str ="color: #3f3; background-color: #AA00ef; and: #abcd";
9
+
let str ="color: #3f3; background-color: #AA00ef; and: #abcd";
10
10
11
-
alert( str.match(re) ); // #3f3 #AA0ef
11
+
alert( str.match(reg) ); // #3f3 #AA0ef
12
12
```
13
13
14
-
P.S. Значения из любого другого количества букв, кроме 3 и 6, такие как `#abcd`, не должны подходить под регэксп.
14
+
P.S. Should be exactly 3 or 6 hex digits: values like `#abcd` should not match.
Без скобок, шаблон `pattern:/go+/`означал бы `subject:g`, после которого идёт одна или более `subject:o`, например: `match:goooo`. А скобки "группируют" `pattern:(go)` вместе.
20
+
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`.
21
21
22
-
## Содержимое группы
22
+
Parentheses group the word `pattern:(go)` together.
23
23
24
-
Скобки нумеруются слева направо. Поисковой движок запоминает содержимое каждой скобки и позволяет обращаться к нему -- в шаблоне и строке замены и, конечно же, в результатах.
25
24
26
-
Например, найти HTML-тег можно шаблоном `pattern:<.*?>`.
25
+
## Contents of parentheses
27
26
28
-
После поиска мы захотим что-то сделать с результатом. Для удобства заключим содержимое `<...>` в скобки: `pattern:<(.*?)>`. Тогда оно будет доступно отдельно.
27
+
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.
29
28
30
-
При поиске методом [String#match](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/String/match) в результирующем массиве будет сначала всё совпадение, а далее -- скобочные группы. В шаблоне `pattern:<(.*?)>` скобочная группа только одна:
29
+
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.
30
+
31
+
If we enclose the inner contents of `<...>` into parentheses, then we can access it like this:
31
32
32
33
```js run
33
-
var str ='<h1>Привет, мир!</h1>';
34
-
var reg =/<(.*?)>/;
34
+
let str ='<h1>Hello, world!</h1>';
35
+
let reg =/<(.*?)>/;
35
36
36
-
alert( str.match(reg) ); //массив: <h1>, h1
37
+
alert( str.match(reg) ); //Array: ["<h1>", "h1"]
37
38
```
38
39
39
-
Заметим, что метод[String#match](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/String/match)выдаёт скобочные группы только при поиске без флага `/.../g`. В примере выше он нашёл только первое совпадение `match:<h1>`, а закрывающий `match:</h1>` не нашёл, поскольку без флага `/.../g`ищется только первое совпадение.
40
+
The call to[String#match](mdn:js/String/match)returns groups only if the regexp has no `pattern:/.../g`flag.
40
41
41
-
Для того, чтобы искать и с флагом `/.../g` и со скобочными группами, используется метод [RegExp#exec](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec):
42
+
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>:
42
43
43
44
```js run
44
-
var str ='<h1>Привет, мир!</h1>';
45
-
var reg =/<(.*?)>/g;
45
+
let str ='<h1>Hello, world!</h1>';
46
+
47
+
// two matches: opening <h1> and closing </h1> tags
48
+
let reg =/<(.*?)>/g;
46
49
47
-
var match;
50
+
let match;
48
51
49
-
while ((match =reg.exec(str)) !==null) {
50
-
//сначала выведет первое совпадение: <h1>,h1
51
-
//затем выведет второе совпадение: </h1>,/h1
52
+
while (match =reg.exec(str)) {
53
+
//first shows the match: <h1>,h1
54
+
//then shows the match: </h1>,/h1
52
55
alert(match);
53
56
}
54
57
```
55
58
56
-
Теперь найдено оба совпадения `pattern:<(.*?)>`, каждое -- массив из полного совпадения и скобочных групп (одна в данном случае).
59
+
Here we have two matches for `pattern:<(.*?)>`, each of them is an array with the full match and groups.
60
+
61
+
## Nested groups
57
62
58
-
## Вложенные группы
59
-
Скобки могут быть и вложенными. В этом случае нумерация также идёт слева направо.
63
+
Parentheses can be nested. In this case the numbering also goes from left to right.
60
64
61
-
Например, при поиске тега в `subject:<span class="my">`нас может интересовать:
65
+
For instance, when searching a tag in `subject:<span class="my">`we may be interested in:
62
66
63
-
1.Содержимое тега целиком: `span class="my"`.
64
-
2.В отдельную переменную для удобства хотелось бы поместить тег: `span`.
65
-
3.Также может быть удобно отдельно выделить атрибуты `class="my"`.
67
+
1.The tag content as a whole: `match:span class="my"`.
На нулевом месте -- всегда совпадение полностью, далее -- группы. Нумерация всегда идёт слева направо, по открывающей скобке.
86
+
At the zero index of the `result` is always the full match.
82
87
83
-
В данном случае получилось, что группа 1 включает в себя содержимое групп 2 и 3. Это совершенно нормальная ситуация, которая возникает, когда нужно выделить что-то отдельное внутри большей группы.
88
+
Then groups, numbered from left to right. Whichever opens first gives the first group `result[1]`. Here it encloses the whole tag content.
84
89
85
-
**Даже если скобочная группа необязательна и не входит в совпадение, соответствующий элемент массива существует (и равен `undefined`).**
90
+
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]`.
86
91
87
-
Например, рассмотрим регэксп `pattern:a(z)?(c)?`. Он ищет `"a"`, за которой не обязательно идёт буква `"z"`, за которой необязательно идёт буква `"c"`.
92
+
**If a group is optional and doesn't exist in the match, the corresponding `result` index is present (and equals `undefined`).**
88
93
89
-
Если напустить его на строку из одной буквы `"a"`, то результат будет таков:
94
+
For instance, let's consider the regexp `pattern:a(z)?(c)?`. It looks for `"a"` optionally followed by `"z"` optionally followed by `"c"`.
95
+
96
+
If we run it on the string with a single letter `subject:a`, then the result is:
90
97
91
98
```js run
92
-
var match ='a'.match(/a(z)?(c)?/)
99
+
let match ='a'.match(/a(z)?(c)?/);
93
100
94
101
alert( match.length ); // 3
95
-
alert( match[0] ); // a
102
+
alert( match[0] ); // a (whole match)
96
103
alert( match[1] ); // undefined
97
104
alert( match[2] ); // undefined
98
105
```
99
106
100
-
Массив получился длины `3`, но все скобочные группы -- `undefined`.
107
+
The array has the length of `3`, but all groups are empty.
101
108
102
-
А теперь более сложная ситуация, строка`subject:ack`:
109
+
And here's a more complex match for the string`subject:ack`:
103
110
104
111
```js run
105
-
var match ='ack'.match(/a(z)?(c)?/)
112
+
let match ='ack'.match(/a(z)?(c)?/)
106
113
107
114
alert( match.length ); // 3
108
-
alert( match[0] ); // ac, всё совпадение
109
-
alert( match[1] ); // undefined, для (z)? ничего нет
115
+
alert( match[0] ); // ac (whole match)
116
+
alert( match[1] ); // undefined, because there's nothing for (z)?
110
117
alert( match[2] ); // c
111
118
```
112
119
113
-
Длина массива результатов по-прежнему `3`. Она постоянна. А вот для скобочной группы `pattern:(z)?` в ней ничего нет, поэтому результат: `["ac", undefined, "c"]`.
114
-
115
-
## Исключение из запоминания через ?:
120
+
The array length is permanent: `3`. But there's nothing for the group `pattern:(z)?`, so the result is `["ac", undefined, "c"]`.
116
121
117
-
Бывает так, что скобки нужны, чтобы квантификатор правильно применился, а вот запоминать их содержимое в массиве не нужно.
122
+
## Non-capturing groups with ?:
118
123
119
-
Скобочную группу можно исключить из запоминаемых и нумеруемых, добавив в её начало `pattern:?:`.
124
+
Sometimes we need parentheses to correctly apply a quantifier, but we don't want their contents in the array.
120
125
121
-
Например, мы хотим найти `pattern:(go)+`, но содержимое скобок (`go`) в отдельный элемент массива выделять не хотим.
126
+
A group may be excluded by adding `pattern:?:` in the beginning.
122
127
123
-
Для этого нужно сразу после открывающей скобки поставить `?:`, то есть: `pattern:(?:go)+`.
128
+
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)+`.
124
129
125
-
Например:
130
+
In the example below we only get the name "John" as a separate member of the `results` array:
126
131
127
132
```js run
128
-
var str ="Gogo John!";
133
+
let str ="Gogo John!";
129
134
*!*
130
-
var reg =/(?:go)+ (\w+)/i;
135
+
// exclude Gogo from capturing
136
+
let reg =/(?:go)+ (\w+)/i;
131
137
*/!*
132
138
133
-
var result =str.match(reg);
139
+
let result =str.match(reg);
134
140
135
141
alert( result.length ); // 2
136
142
alert( result[1] ); // John
137
143
```
138
-
139
-
В примере выше массив результатов имеет длину `2` и содержит только полное совпадение и результат `pattern:(\w+)`. Это удобно в тех случаях, когда содержимое скобок нас не интересует.
0 commit comments