Skip to content

Commit 60b7b26

Browse files
committed
9-regular-expressions/07-regexp-quantifiers/article.md
1 parent b98ed4b commit 60b7b26

1 file changed

Lines changed: 52 additions & 50 deletions

File tree

  • 9-regular-expressions/07-regexp-quantifiers
Lines changed: 52 additions & 50 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,77 @@ 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
9494
// 1 not matched, as 0+ requires at least one zero
95+
// 1 не подходит, т.к 0+ требует как минимум один ноль
9596
```
9697

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

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

101-
Regexp "decimal fraction" (a number with a floating point): `pattern:\d+\.\d+`
102-
: In action:
102+
Регэксп «десятичная дробь» (число с плавающей точкой): `pattern:\d+\.\d+`
103+
: В действии:
103104
```js run
104105
alert( "0 1 12.345 7890".match(/\d+\.\d+/g) ); // 12.345
105106
```
106107

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

110111
```js run
111112
alert( "<body> ... </body>".match(/<[a-z]+>/gi) ); // <body>
112113
```
113114

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

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>`.
117+
Регэксп «открывающий HTML-тег без атрибутов» (лучше): `pattern:/<[a-z][a-z0-9]*>/i`
118+
: Здесь регулярное выражение расширено: в соответствие со стандартом, HTML-тег может иметь символ цифры на любой позиции, кроме первой, например `<h1>`.
118119

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

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.
124+
Регэксп «открывающий или закрывающий HTML-тег без атрибутов»: `pattern:/<\/?[a-z][a-z0-9]*>/i`
125+
: В предыдущий паттерн мы добавили необязательный `pattern:/?`. Его понадобилось заэкранировать, чтобы JavaScript не принял его за конец шаблона.
125126

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

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.
131+
```smart header="Чтобы регулярное выражение было точнее, нам часто приходится делать его сложнее"
132132
133-
For instance, for HTML tags we could use a simpler regexp: `pattern:<\w+>`.
133+
В этих примерах мы видим общее правило: чем точнее регулярное выражение -- тем оно длиннее и сложнее.
134134
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.
135+
Например, для HTML-тегов, скорее всего, подошло бы и более простое регулярное выражение : `pattern:<\w+>`.
136136
137-
Are we ok with `pattern:<\w+>` or we need `pattern:<[a-z][a-z0-9]*>`?
137+
...Но т.к класс `pattern:\w` означает любую английскую букву или цифру или `'_'`, то для такого регэксп подойдут и не теги, например `match:<_>`. Однако он гораздо проще, чем регэксп `pattern:<[a-z][a-z0-9]*>`, но менее точный.
138138
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.
139+
Подойдёт ли нам `pattern:<\w+>` или нужно использовать `pattern:<[a-z][a-z0-9]*>`?
140+
141+
В реальной жизни допустимы оба варианта. Ответ на подобные вопросы зависит от того, насколько реально важна точность и насколько потом будет сложно или не сложно отфильтровать лишние совпадения.
140142
```

0 commit comments

Comments
 (0)