Skip to content

Commit 93db6f2

Browse files
Merge pull request #150 from oshliaer/9-regular-expressions_05-regexp-character-sets-and-ranges-article_md_ru
Init 9-regular-expressions_05-regexp-character-sets-and-ranges-articl…
2 parents cce0129 + b451ed1 commit 93db6f2

File tree

1 file changed

+54
-54
lines changed
  • 9-regular-expressions/05-regexp-character-sets-and-ranges

1 file changed

+54
-54
lines changed
Lines changed: 54 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1,114 +1,114 @@
1-
# Sets and ranges [...]
1+
# Наборы и диапазоны [...]
22

3-
Several characters or character classes inside square brackets `[…]` mean to "search for any character among given".
3+
Несколько символов или символьных классов в квадратных скобках `[…]` означают "искать любой символ из заданных".
44

5-
## Sets
5+
## Наборы
66

7-
For instance, `pattern:[eao]` means any of the 3 characters: `'a'`, `'e'`, or `'o'`.
7+
Для примера, `pattern:[eao]` означает любой из 3-х символов: `'a'`, `'e'` или `'o'`.
88

9-
That's called a *set*. Sets can be used in a regexp along with regular characters:
9+
Это называется *набором*. Наборы могут использоваться в регулярных выражениях вместе с обычными символами:
1010

1111
```js run
12-
// find [t or m], and then "op"
12+
// найти [t или m], а за ними "op"
1313
alert( "Mop top".match(/[tm]op/gi) ); // "Mop", "top"
1414
```
1515

16-
Please note that although there are multiple characters in the set, they correspond to exactly one character in the match.
16+
Обратите внимание, что в наборе несколько символов, но в результате он соответствует ровно одному символу.
1717

18-
So the example above gives no matches:
18+
Так что приведенный ниже пример не дает совпадений:
1919

2020
```js run
21-
// find "V", then [o or i], then "la"
22-
alert( "Voila".match(/V[oi]la/) ); // null, no matches
21+
// найти "V", затем [o или i], потом "la"
22+
alert( "Voila".match(/V[oi]la/) ); // null, нет совпадений
2323
```
2424

25-
The pattern assumes:
25+
Шаблон предполагает:
2626

2727
- `pattern:V`,
28-
- then *one* of the letters `pattern:[oi]`,
29-
- then `pattern:la`.
28+
- затем *один* из символов `pattern:[oi]`,
29+
- потом `pattern:la`.
3030

31-
So there would be a match for `match:Vola` or `match:Vila`.
31+
В этом случае совпадениями могут быть `match:Vola` или `match:Vila`.
3232

33-
## Ranges
33+
## Диапазоны
3434

35-
Square brackets may also contain *character ranges*.
35+
Еще квадратные скобки могут содержать *диапазоны символов*.
3636

37-
For instance, `pattern:[a-z]` is a character in range from `a` to `z`, and `pattern:[0-5]` is a digit from `0` to `5`.
37+
К примеру, `pattern:[a-z]` соответствует символу в диапазоне от `a` до `z`, или `pattern:[0-5]` -- цифра от `0` до `5`.
3838

39-
In the example below we're searching for `"x"` followed by two digits or letters from `A` to `F`:
39+
В приведенном ниже примере мы ищем `"x"`, за которым следуют две цифры или буквы от `A` до `F`:
4040

4141
```js run
4242
alert( "Exception 0xAF".match(/x[0-9A-F][0-9A-F]/g) ); // xAF
4343
```
4444

45-
Please note that in the word `subject:Exception` there's a substring `subject:xce`. It didn't match the pattern, because the letters are lowercase, while in the set `pattern:[0-9A-F]` they are uppercase.
45+
Обратите внимание, что в слове `subject:Exception` есть подстрока `subject:xce`. Это не соответствует шаблону, потому что буквы строчные, а в наборе `pattern:[0-9A-F]` они прописные.
4646

47-
If we want to find it too, then we can add a range `a-f`: `pattern:[0-9A-Fa-f]`. The `i` flag would allow lowercase too.
47+
Если мы хотим найти и то и другое, то мы можем добавить еще диапазон `a-f`: `pattern:[0-9A-Fa-f]`. Флаг `i` также допускает использование строчных букв.
4848

49-
**Character classes are shorthands for certain character sets.**
49+
**Символьные Классы являются сокращениями для определенных наборов символов.**
5050

51-
For instance:
51+
Например:
5252

53-
- **\d** -- is the same as `pattern:[0-9]`,
54-
- **\w** -- is the same as `pattern:[a-zA-Z0-9_]`,
55-
- **\s** -- is the same as `pattern:[\t\n\v\f\r ]` plus few other unicode space characters.
53+
- **\d** -- то же самое, что и `pattern:[0-9]`,
54+
- **\w** -- то же самое, что и `pattern:[a-zA-Z0-9_]`,
55+
- **\s** -- то же самое, что и `pattern:[\t\n\v\f\r ]` плюс несколько других символов Юникода.
5656

57-
We can use character classes inside `[…]` as well.
57+
Еще мы можем использовать символьные классы внутри `[…]`.
5858

59-
For instance, we want to match all wordly characters or a dash, for words like "twenty-third". We can't do it with `pattern:\w+`, because `pattern:\w` class does not include a dash. But we can use `pattern:[\w-]`.
59+
Например, мы хотим найти все символы, используемые в словах, а также тире, чтобы найти слова вида "twenty-third". Мы не можем сделать это с помощью `pattern:\w+`, потому что класс `pattern:\w` не содержит тире. Но можно использовать `pattern:[\w-]`.
6060

61-
We also can use a combination of classes to cover every possible character, like `pattern:[\s\S]`. That matches spaces or non-spaces -- any character. That's wider than a dot `"."`, because the dot matches any character except a newline.
61+
Можем использовать и несколько классов вместе, например `pattern:[\s\S]` означает "пробельные символы или не-пробельные символы" -- то есть, вообще, любой символ. Это шире, чем точка `"."`, так как точка соответствует любому символу, кроме перевода строки (если не указан флаг `s`).
6262

63-
## Excluding ranges
63+
## Исключающие диапазоны
6464

65-
Besides normal ranges, there are "excluding" ranges that look like `pattern:[^…]`.
65+
Помимо обычных диапазонов, есть "исключающие" диапазоны, которые выглядят как `pattern:[^…]`.
6666

67-
They are denoted by a caret character `^` at the start and match any character *except the given ones*.
67+
Они обозначаются символом каретки `^` в начале диапазона и соответствуют любому символу *за исключением заданных*.
6868

69-
For instance:
69+
Например:
7070

71-
- `pattern:[^aeyo]` -- any character except `'a'`, `'e'`, `'y'` or `'o'`.
72-
- `pattern:[^0-9]` -- any character except a digit, the same as `\D`.
73-
- `pattern:[^\s]` -- any non-space character, same as `\S`.
71+
- `pattern:[^aeyo]` -- любой символ, за исключением `'a'`, `'e'`, `'y'` или `'o'`.
72+
- `pattern:[^0-9]` -- любой символ, за исключением цифры, то же, что и `\D`.
73+
- `pattern:[^\s]` -- любой непробельный символ, то же, что и `\S`.
7474

75-
The example below looks for any characters except letters, digits and spaces:
75+
Пример ниже ищет любые символы, кроме букв, цифр и пробелов:
7676

7777
```js run
78-
alert( "alice15@gmail.com".match(/[^\d\sA-Z]/gi) ); // @ and .
78+
alert( "alice15@gmail.com".match(/[^\d\sA-Z]/gi) ); // @ и .
7979
```
8080

81-
## No escaping in []
81+
## В экранировании нет необходимости
8282

83-
Usually when we want to find exactly the dot character, we need to escape it like `pattern:\.`. And if we need a backslash, then we use `pattern:\\`.
83+
Обычно, когда мы хотим найти именно точку, нам нужно экранировать её как `pattern:\.`. А если нам нужна обратная косая черта, тогда используем `pattern:\\`.
8484

85-
In square brackets the vast majority of special characters can be used without escaping:
85+
В квадратных скобках большинство специальных символов можно использовать без экранирования:
8686

87-
- A dot `pattern:'.'`.
88-
- A plus `pattern:'+'`.
89-
- Parentheses `pattern:'( )'`.
90-
- Dash `pattern:'-'` in the beginning or the end (where it does not define a range).
91-
- A caret `pattern:'^'` if not in the beginning (where it means exclusion).
92-
- And the opening square bracket `pattern:'['`.
87+
- Точка `pattern:'.'`.
88+
- Плюс `pattern:'+'`.
89+
- Круглые скобки `pattern:'( )'`.
90+
- Тире `pattern:'-'` в начале или в конце (где этот символ не определяет диапазон).
91+
- Символ каретки `pattern:'^'`, если не в начале (где это означает исключение).
92+
- И открывающая квадратная скобка `pattern:'['`.
9393

94-
In other words, all special characters are allowed except where they mean something for square brackets.
94+
Другими словами, разрешены все специальные символы, кроме случаев, когда они означают что-то особое для диапазонов.
9595

96-
A dot `"."` inside square brackets means just a dot. The pattern `pattern:[.,]` would look for one of characters: either a dot or a comma.
96+
Точка `"."` внутри квадратных скобок -- просто точка. Шаблон `pattern:[.,]` будет искать один из символов: точку или запятую.
9797

98-
In the example below the regexp `pattern:[-().^+]` looks for one of the characters `-().^+`:
98+
В приведенном ниже примере регулярное выражение `pattern:[-().^+]` ищет один из символов `-().^+`:
9999

100100
```js run
101-
// No need to escape
101+
// Нет необходимости в экранировании
102102
let reg = /[-().^+]/g;
103103

104-
alert( "1 + 2 - 3".match(reg) ); // Matches +, -
104+
alert( "1 + 2 - 3".match(reg) ); // Совпадения +, -
105105
```
106106

107-
...But if you decide to escape them "just in case", then there would be no harm:
107+
...Но если вы решите экранировать "на всякий случай", то не будет никакого вреда:
108108

109109
```js run
110-
// Escaped everything
110+
// Экранирование всех возможных символов
111111
let reg = /[\-\(\)\.\^\+]/g;
112112

113-
alert( "1 + 2 - 3".match(reg) ); // also works: +, -
113+
alert( "1 + 2 - 3".match(reg) ); // также работает: +, -
114114
```

0 commit comments

Comments
 (0)