Skip to content

Commit 7c5d1fd

Browse files
Merge pull request #188 from dmitrylebedev/master
9-regular-expressions/07-regexp-quantifiers/article.md
2 parents be65500 + b6b017b commit 7c5d1fd

5 files changed

Lines changed: 73 additions & 72 deletions

File tree

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11

2-
Solution:
2+
Решение:
33

44
```js run
55
let reg = /\.{3,}/g;
6-
alert( "Hello!... How goes?.....".match(reg) ); // ..., .....
6+
alert( "Привет!... Как дела?.....".match(reg) ); // ..., .....
77
```
88

9-
Please note that the dot is a special character, so we have to escape it and insert as `\.`.
9+
Обратите внимание, что точка - это специальный символ. Мы должны экранировать её, то есть вставлять как `\.`.

9-regular-expressions/07-regexp-quantifiers/1-find-text-manydots/task.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@ importance: 5
22

33
---
44

5-
# How to find an ellipsis "..." ?
5+
# Как найти многоточие "..." ?
66

7-
Create a regexp to find ellipsis: 3 (or more?) dots in a row.
7+
Напишите регулярное выражение, которое ищет многоточие (3 и более точек подряд).
88

9-
Check it:
9+
Проверьте его:
1010

1111
```js
12-
let reg = /your regexp/g;
13-
alert( "Hello!... How goes?.....".match(reg) ); // ..., .....
12+
let reg = /ваше выражение/g;
13+
alert( "Привет!... Как дела?.....".match(reg) ); // ..., .....
1414
```
Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
We need to look for `#` followed by 6 hexadimal characters.
1+
Нам нужно найти символ `#`, за которым следуют 6 шестнадцатеричных символов.
22

3-
A hexadimal character can be described as `pattern:[0-9a-fA-F]`. Or if we use the `i` flag, then just `pattern:[0-9a-f]`.
3+
Шестнадцатеричный символ может быть описан с помощью регулярного выражения как `pattern:[0-9a-fA-F]`. Или же как `pattern:[0-9a-f]`, если мы используем модификатор `i`.
44

5-
Then we can look for 6 of them using the quantifier `pattern:{6}`.
5+
Затем мы можем добавить квантификатор `pattern:{6}`, так как нам нужно 6 таких символов.
66

7-
As a result, we have the regexp: `pattern:/#[a-f0-9]{6}/gi`.
7+
В результате наше регулярное выражение получилось таким: `pattern:/#[a-f0-9]{6}/gi`.
88

99
```js run
1010
let reg = /#[a-f0-9]{6}/gi;
@@ -14,18 +14,18 @@ let str = "color:#121212; background-color:#AA00ef bad-colors:f#fddee #fd2"
1414
alert( str.match(reg) ); // #121212,#AA00ef
1515
```
1616

17-
The problem is that it finds the color in longer sequences:
17+
Проблема в том, что находятся также совпадения, принадлежащие более длинным последовательностям символов:
1818

1919
```js run
2020
alert( "#12345678".match( /#[a-f0-9]{6}/gi ) ) // #12345678
2121
```
2222

23-
To fix that, we can add `pattern:\b` to the end:
23+
Чтобы исправить это, мы можем добавить в конец нашего регулярного выражения `pattern:\b`:
2424

2525
```js run
26-
// color
26+
// цвет
2727
alert( "#123456".match( /#[a-f0-9]{6}\b/gi ) ); // #123456
2828

29-
// not a color
29+
// не цвет
3030
alert( "#12345678".match( /#[a-f0-9]{6}\b/gi ) ); // null
3131
```
Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
1-
# Regexp for HTML colors
1+
# Регулярное выражение для HTML-цветов
22

3-
Create a regexp to search HTML-colors written as `#ABCDEF`: first `#` and then 6 hexadimal characters.
3+
Напишите регулярное выражение, которое ищет HTML-цвета в формате `#ABCDEF`: первым идёт символ `#`, и потом - 6 шестнадцатеричных символов.
44

5-
An example of use:
5+
Пример использования:
66

77
```js
8-
let reg = /...your regexp.../
8+
let reg = /...ваше выражение.../
99

1010
let str = "color:#121212; background-color:#AA00ef bad-colors:f#fddee #fd2 #12345678";
1111

1212
alert( str.match(reg) ) // #121212,#AA00ef
1313
```
1414

15-
P.S. In this task we do not need other color formats like `#123` or `rgb(1,2,3)` etc.
15+
P.S. В рамках этого задания не нужно искать цвета, записанные в иных форматах типа `#123` или `rgb(1,2,3)`.
Lines changed: 52 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,46 @@
1-
# Quantifiers +, *, ? and {n}
1+
# Квантификаторы +, *, ? и {n}
22

3-
Let's say we have a string like `+7(903)-123-45-67` and want to find all numbers in it. But unlike before, we are interested not in single digits, but full numbers: `7, 903, 123, 45, 67`.
3+
Давайте возьмём строку вида `+7(903)-123-45-67` и найдём все числа в ней. Но теперь нас интересуют не цифры по отдельности, а именно числа: `7, 903, 123, 45, 67`.
44

5-
A number is a sequence of 1 or more digits `\d`. To mark how many we need, we need to append a *quantifier*.
5+
Число — это последовательность из 1 или более цифр `\d`. Чтобы отметить количество повторений, нам нужно указать *квантификатор*.
66

7-
## Quantity {n}
7+
## Количество {n}
88

9-
The simplest quantifier is a number in curly braces: `pattern:{n}`.
9+
Самый простой квантификатор — это число в фигурных скобках: `pattern:{n}`.
1010

11-
A quantifier is appended to a character (or a character class, or a `[...]` set etc) and specifies how many we need.
11+
Он добавляется к символу (или символьному классу, или набору `[...]` и т.д.) и указывает, сколько их нам нужно.
1212

13-
It has a few advanced forms, let's see examples:
13+
У него есть несколько вариантов, давайте посмотрим примеры:
1414

15-
The exact count: `{5}`
16-
: `pattern:\d{5}` denotes exactly 5 digits, the same as `pattern:\d\d\d\d\d`.
15+
Точное количество: `{5}`
16+
: Шаблон `pattern:\d{5}` обозначает ровно 5 цифр, он эквивалентен `pattern:\d\d\d\d\d`.
1717

18-
The example below looks for a 5-digit number:
18+
Следующий пример находит пятизначное число:
1919

2020
```js run
21-
alert( "I'm 12345 years old".match(/\d{5}/) ); // "12345"
21+
alert( "Мне 12345 лет".match(/\d{5}/) ); // "12345"
2222
```
2323

24-
We can add `\b` to exclude longer numbers: `pattern:\b\d{5}\b`.
24+
Мы можем добавить `\b`, чтобы исключить числа длиннее: `pattern:\b\d{5}\b`.
2525

26-
The range: `{3,5}`, match 3-5 times
27-
: To find numbers from 3 to 5 digits we can put the limits into curly braces: `pattern:\d{3,5}`
26+
Диапазон: `{3,5}`, от 3 до 5
27+
: Для того, чтобы найти числа c разрядностью от 3 до 5 цифр, мы можем указать границы в фигурных скобках: `pattern:\d{3,5}`
2828

2929
```js run
30-
alert( "I'm not 12, but 1234 years old".match(/\d{3,5}/) ); // "1234"
30+
alert( "Мне не 12, а 1234 года".match(/\d{3,5}/) ); // "1234"
3131
```
3232

33-
We can omit the upper limit.
33+
Верхнюю границу можно не указывать.
3434

35-
Then a regexp `pattern:\d{3,}` looks for sequences of digits of length `3` or more:
35+
Тогда шаблон `pattern:\d{3,}` найдет последовательность чисел длиной `3` и более цифр:
3636

3737
```js run
38-
alert( "I'm not 12, but 345678 years old".match(/\d{3,}/) ); // "345678"
38+
alert( "Мне не 12, а 345678 лет".match(/\d{3,}/) ); // "345678"
3939
```
4040

41-
Let's return to the string `+7(903)-123-45-67`.
41+
Давайте вернёмся к строке `+7(903)-123-45-67`.
4242

43-
A number is a sequence of one or more digits in a row. So the regexp is `pattern:\d{1,}`:
43+
Число - это последовательность из одной или более цифр. Поэтому шаблон будет `pattern:\d{1,}`:
4444

4545
```js run
4646
let str = "+7(903)-123-45-67";
@@ -50,14 +50,14 @@ let numbers = str.match(/\d{1,}/g);
5050
alert(numbers); // 7,903,123,45,67
5151
```
5252

53-
## Shorthands
53+
## Короткие обозначения
5454

55-
There are shorthands for most used quantifiers:
55+
Для самых востребованных квантификаторов есть сокращённые формы записи:
5656

5757
`+`
58-
: Means "one or more", the same as `{1,}`.
58+
: Означает "один или более". То же самое, что и `{1,}`.
5959

60-
For instance, `pattern:\d+` looks for numbers:
60+
Например, `pattern:\d+` находит числа:
6161

6262
```js run
6363
let str = "+7(903)-123-45-67";
@@ -66,75 +66,76 @@ There are shorthands for most used quantifiers:
6666
```
6767

6868
`?`
69-
: Means "zero or one", the same as `{0,1}`. In other words, it makes the symbol optional.
69+
: Означает "ноль или один". То же самое, что и `{0,1}`. По сути, делает символ необязательным.
7070

71-
For instance, the pattern `pattern:ou?r` looks for `match:o` followed by zero or one `match:u`, and then `match:r`.
71+
Например, шаблон `pattern:ou?r` найдёт `match:o` после которого, возможно, следует `match:u`, а затем `match:r`.
7272

73-
So, `pattern:colou?r` finds both `match:color` and `match:colour`:
73+
Поэтому шаблон `pattern:colou?r` найдёт оба: `match:color` и `match:colour`:
7474

7575
```js run
76-
let str = "Should I write color or colour?";
76+
let str = "Следует писать color или colour?";
7777

7878
alert( str.match(/colou?r/g) ); // color, colour
7979
```
8080

8181
`*`
82-
: Means "zero or more", the same as `{0,}`. That is, the character may repeat any times or be absent.
82+
: Означает "ноль или более". То же самое, что и `{0,}`. То есть символ может повторяться много раз или вообще отсутствовать.
8383

84-
For example, `pattern:\d0*` looks for a digit followed by any number of zeroes:
84+
Например, шаблон `pattern:\d0*` находит цифру вместе со всеми нулями, которые идут за ней (но могут и не идти):
8585

8686
```js run
8787
alert( "100 10 1".match(/\d0*/g) ); // 100, 10, 1
8888
```
8989

90-
Compare it with `'+'` (one or more):
90+
Сравните это с `'+'` (один или более):
9191

9292
```js run
9393
alert( "100 10 1".match(/\d0+/g) ); // 100, 10
94-
// 1 not matched, as 0+ requires at least one zero
94+
// 1 не подходит, т.к 0+ требует как минимум один ноль
9595
```
9696

97-
## More examples
97+
## Ещё примеры
9898

99-
Quantifiers are used very often. They serve as the main "building block" of complex regular expressions, so let's see more examples.
99+
Квантификаторы используются очень часто. Они служат основными "строительными блоками" сложных регулярных выражений, поэтому давайте рассмотрим ещё примеры.
100100

101-
Regexp "decimal fraction" (a number with a floating point): `pattern:\d+\.\d+`
102-
: In action:
101+
Регулярное выражение для поиска десятичных дробей (чисел с плавающей точкой): `pattern:\d+\.\d+`
102+
: В действии:
103103
```js run
104104
alert( "0 1 12.345 7890".match(/\d+\.\d+/g) ); // 12.345
105105
```
106106

107-
Regexp "open HTML-tag without attributes", like `<span>` or `<p>`: `pattern:/<[a-z]+>/i`
108-
: In action:
107+
Регулярное выражение для поиска "открывающего HTML-тега без атрибутов". Например, `<span>` или `<p>`: `pattern:/<[a-z]+>/i`
108+
: В действии:
109109

110110
```js run
111111
alert( "<body> ... </body>".match(/<[a-z]+>/gi) ); // <body>
112112
```
113113

114-
We look for character `pattern:'<'` followed by one or more English letters, and then `pattern:'>'`.
114+
Это регулярное выражение ищет символ `pattern:'<'`, за которым идут одна или более букв английского алфавита, а затем `pattern:'>'`.
115115

116-
Regexp "open HTML-tag without attributes" (improved): `pattern:/<[a-z][a-z0-9]*>/i`
117-
: Better regexp: according to the standard, HTML tag name may have a digit at any position except the first one, like `<h1>`.
116+
Регулярное выражение для поиска "открывающего HTML-тега без атрибутов" (улучшенный вариант): `pattern:/<[a-z][a-z0-9]*>/i`
117+
: Здесь регулярное выражение расширено: в соответствие со стандартом, в названии HTML-тега цифра может быть на любой позиции, кроме первой, например `<h1>`.
118118

119119
```js run
120-
alert( "<h1>Hi!</h1>".match(/<[a-z][a-z0-9]*>/gi) ); // <h1>
120+
alert( "<h1>Привет!</h1>".match(/<[a-z][a-z0-9]*>/gi) ); // <h1>
121121
```
122122

123-
Regexp "opening or closing HTML-tag without attributes": `pattern:/<\/?[a-z][a-z0-9]*>/i`
124-
: We added an optional slash `pattern:/?` before the tag. Had to escape it with a backslash, otherwise JavaScript would think it is the pattern end.
123+
Регулярное выражение для поиска "открывающего или закрывающего HTML-тега без атрибутов": `pattern:/<\/?[a-z][a-z0-9]*>/i`
124+
: В предыдущий шаблон мы добавили необязательный слеш `pattern:/?`. Этот символ понадобилось заэкранировать, чтобы JavaScript не принял его за конец шаблона.
125125

126126
```js run
127-
alert( "<h1>Hi!</h1>".match(/<\/?[a-z][a-z0-9]*>/gi) ); // <h1>, </h1>
127+
alert( "<h1>Привет!</h1>".match(/<\/?[a-z][a-z0-9]*>/gi) ); // <h1>, </h1>
128128
```
129129

130-
```smart header="To make a regexp more precise, we often need make it more complex"
131-
We can see one common rule in these examples: the more precise is the regular expression -- the longer and more complex it is.
130+
```smart header="Чтобы регулярное выражение было точнее, нам часто приходится делать его сложнее"
132131
133-
For instance, for HTML tags we could use a simpler regexp: `pattern:<\w+>`.
132+
В этих примерах мы видим общее правило: чем точнее регулярное выражение -- тем оно длиннее и сложнее.
134133
135-
...But because `pattern:\w` means any English letter or a digit or `'_'`, the regexp also matches non-tags, for instance `match:<_>`. So it's much simpler than `pattern:<[a-z][a-z0-9]*>`, but less reliable.
134+
Например, для HTML-тегов, скорее всего, подошло бы и более простое регулярное выражение: `pattern:<\w+>`.
136135
137-
Are we ok with `pattern:<\w+>` or we need `pattern:<[a-z][a-z0-9]*>`?
136+
...Но так как класс `pattern:\w` означает любую английскую букву или цифру, или `'_'`, то для такого регулярного выражения подойдут и не теги, например `match:<_>`. То есть оно гораздо проще, чем шаблон `pattern:<[a-z][a-z0-9]*>`, но вместе с тем и менее точное.
138137
139-
In real life both variants are acceptable. Depends on how tolerant we can be to "extra" matches and whether it's difficult or not to filter them out by other means.
138+
Подойдёт ли нам `pattern:<\w+>` или нужно использовать `pattern:<[a-z][a-z0-9]*>`?
139+
140+
В реальной жизни допустимы оба варианта. Ответ на подобные вопросы зависит от того, насколько реально важна точность и насколько потом будет сложно или несложно отфильтровать лишние совпадения.
140141
```

0 commit comments

Comments
 (0)