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
Copy file name to clipboardExpand all lines: 9-regular-expressions/03-regexp-character-classes/article.md
+47-46Lines changed: 47 additions & 46 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,14 +1,14 @@
1
-
# Character classes
1
+
# Классы символов
2
2
3
-
Consider a practical task -- we have a phone number`"+7(903)-123-45-67"`, and we need to turn it into pure numbers: `79035419441`.
3
+
Рассмотрим практическую задачу - у нас есть номер телефона`"+7(903)-123-45-67"`, и нам нужно превратить его в строку только из чисел: `79035419441`.
4
4
5
-
To do so, we can find and remove anything that's not a number. Character classes can help with that.
5
+
Для этого мы можем найти и удалить все, что не является числом. Классы символов могут помочь с этим.
6
6
7
-
A character class is a special notation that matches any symbol from a certain set.
7
+
Класс символов - это специальное обозначение, которое соответствует любому символу из определенного набора.
8
8
9
-
For the start, let's explore a "digit" class. It's written as`\d`. We put it in the pattern, that means "any single digit".
9
+
Для начала давайте рассмотрим класс "цифр". Он обозначается как`\d`. Мы помещаем это обозначение в регулярное выражение, что соответствует "любой одной цифре".
10
10
11
-
For instance, the let's find the first digit in the phone number:
11
+
Например, давайте найдем первую цифру в номере телефона:
12
12
13
13
```js run
14
14
let str ="+7(903)-123-45-67";
@@ -18,99 +18,100 @@ let reg = /\d/;
18
18
alert( str.match(reg) ); // 7
19
19
```
20
20
21
-
Without the flag `g`, the regular expression only looks for the first match, that is the first digit `\d`.
21
+
Без флага `g` регулярное выражение ищет только первое совпадение, то есть первую цифру `\ d`.
22
22
23
-
Let's add the`g` flag to find all digits:
23
+
Давайте добавим флаг`g`, чтобы найти все цифры:
24
24
25
25
```js run
26
26
let str ="+7(903)-123-45-67";
27
27
28
28
let reg =/\d/g;
29
29
30
-
alert( str.match(reg) ); //array of matches: 7,9,0,3,1,2,3,4,5,6,7
That was a character class for digits. There are other character classes as well.
35
+
Это был класс символов для цифр. Есть и другие подобные классы.
36
36
37
-
Most used are:
37
+
Наиболее используемые:
38
38
39
-
`\d` ("d" is from "digit")
40
-
: A digit: a character from `0`to`9`.
39
+
`\d` ("d": от английского "digit" – "цифра")
40
+
: Цифра: символ от `0`до`9`.
41
41
42
-
`\s` ("s" is from "space")
43
-
: A space symbol: that includes spaces, tabs, newlines.
42
+
`\s` ("s": от английского "space" – "пробел")
43
+
: Символ пробела: включает пробелы, символы табуляции, переводы строк.
44
44
45
-
`\w` ("w" is from "word")
46
-
: A "wordly" character: either a letter of English alphabet or a digit or an underscore. Non-english letters (like cyrillic or hindi) do not belong to `\w`.
45
+
`\w` ("w": от английского "word" – "слово")
46
+
: Символ «слова», а точнее – буква латинского алфавита или цифра или подчёркивание '_'. Не-английские буквы не являются частью `\w`, то есть русская буква не подходит.
47
47
48
-
For instance, `pattern:\d\s\w`means a "digit" followed by a "space character" followed by a "wordly character", like`"1 a"`.
48
+
Для примера, `pattern:\d\s\w`обозначает цифру, за которой идёт пробельный символ, а затем символ слова, как в строке`"1 a"`.
49
49
50
-
**A regexp may contain both regular symbols and character classes.**
50
+
**Регулярное выражение может содержать как обычные символы, так и классы символов.**
51
51
52
-
For instance, `pattern:CSS\d`matches a string `match:CSS`with a digit after it:
52
+
Например, `pattern:CSS\d`соответствует строке`match:CSS`с цифрой после нее:
53
53
54
54
```js run
55
-
let str ="CSS4 is cool";
55
+
let str ="Стандарт CSS4 - это здорово";
56
56
let reg =/CSS\d/
57
57
58
58
alert( str.match(reg) ); // CSS4
59
59
```
60
60
61
-
Also we can use many character classes:
61
+
Также мы можем использовать несколько классов символов одновременно:
62
62
63
63
```js run
64
-
alert( "I love HTML5!".match(/\s\w\w\w\w\d/) ); // 'HTML5'
The boundary has "zero width" in a sense that usually a character class means a character in the result (like a wordly character or a digit), but not in this case.
84
+
Граница имеет "нулевую ширину" в том смысле, что обычно класс символов означает символ в результате (например, символ или цифру), но не в этом случае.
85
85
86
-
The boundary is a test.
86
+
Граница – это проверка.
87
87
88
-
When regular expression engine is doing the search, it's moving along the string in an attempt to find the match. At each string position it tries to find the pattern.
88
+
Когда механизм регулярных выражений выполняет поиск, он перемещается по строке в попытке найти совпадение. В каждой позиции строки он пытается найти шаблон.
89
89
90
-
When the pattern contains `pattern:\b`, it tests that the position in string is a word boundary, that is one of three variants:
90
+
Когда шаблон содержит `pattern:\b`, он проверяет, что позиция в строке является границей слова, то есть одним из трех вариантов:
91
91
92
-
-Immediately before is `\w`, and immediately after -- not`\w`, or vise versa.
93
-
-At string start, and the first string character is`\w`.
94
-
-At string end, and the last string character is`\w`.
92
+
-Внутри текста, если с одной стороны `\w`, а с другой – не`\w`.
93
+
-Начало текста, если первый символ`\w`.
94
+
-Конец текста, если последний символ`\w`.
95
95
96
-
For instance, in the string `subject:Hello, Java!`the following positions match`\b`:
96
+
Например, в строке `subject:Привет, Java!`Следующие позиции соответствуют`\b`:
97
97
98
98

99
99
100
-
So it matches `pattern:\bHello\b`, because:
100
+
Так что это соответствует `pattern:\bПривет\b`, потому что:
101
101
102
-
1.At the beginning of the string the first `\b` test matches.
103
-
2.Then the word `Hello` matches.
104
-
3.Then`\b`matches, as we're between `o` and a space.
102
+
1.В начале строки совпадает первый тест `\b`.
103
+
2.Далее слово `Привет` совпадает.
104
+
3.Далее`\b`снова совпадает, так как мы находимся между `т` и пробелом.
105
105
106
106
Pattern `pattern:\bJava\b` also matches. But not `pattern:\bHell\b` (because there's no word boundary after `l`) and not `Java!\b` (because the exclamation sign is not a wordly character, so there's no word boundary after it).
107
+
Pattern `pattern:\bJava\b` также совпадает. Но не `pattern:\bПривед\b` (потому что после `д` нет границы слова), и не `Java!\b` (потому что восклицательный знак не является словесным символом, поэтому после него нет границы слова).
alert( "Привет, Java!".match(/\bПривед\b/) ); // null (no match)
114
+
alert( "Привет, Java!".match(/\bJava!\b/) ); // null (no match)
114
115
```
115
116
116
117
Once again let's note that `pattern:\b` makes the searching engine to test for the boundary, so that `pattern:Java\b` finds `match:Java` only when followed by a word boundary, but it does not add a letter to the result. §
0 commit comments