Skip to content

Commit c9192b1

Browse files
authored
Merge pull request #383 from AntonBurchak/translation/character-classes
Character Classes
2 parents b994a39 + 85ac422 commit c9192b1

File tree

1 file changed

+85
-85
lines changed
  • 9-regular-expressions/02-regexp-character-classes

1 file changed

+85
-85
lines changed
Lines changed: 85 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -1,203 +1,203 @@
1-
# Character classes
1+
# Символьні класи
22

3-
Consider a practical task -- we have a phone number like `"+7(903)-123-45-67"`, and we need to turn it into pure numbers: `79031234567`.
3+
Розглянемо практичне завдання -- у нас є номер телефону типу `"+1(703)-123-45-67"`, і нам потрібно перетворити його на рядок тільки з чисел: `17031234567`.
44

5-
To do so, we can find and remove anything that's not a number. Character classes can help with that.
5+
Для цього ми можемо знайти та видалити все, що не є числом. Із цим нам допоможуть символьні класи.
66

7-
A *character class* is a special notation that matches any symbol from a certain set.
7+
*Символьний клас* -- це спеціальне позначення, яке відповідає будь-якому символу з певного набору.
88

9-
For the start, let's explore the "digit" class. It's written as `pattern:\d` and corresponds to "any single digit".
9+
Для початку давайте розглянемо клас "цифра". Він позначається як `pattern:\d` і відповідає "будь-якій одній цифрі".
1010

11-
For instance, let's find the first digit in the phone number:
11+
Наприклад, знайдемо першу цифру в номері телефону:
1212

1313
```js run
14-
let str = "+7(903)-123-45-67";
14+
let str = "+1(703)-123-45-67";
1515

1616
let regexp = /\d/;
1717

18-
alert( str.match(regexp) ); // 7
18+
alert( str.match(regexp) ); // 1
1919
```
2020

21-
Without the flag `pattern:g`, the regular expression only looks for the first match, that is the first digit `pattern:\d`.
21+
Без прапора `pattern:g` регулярний вираз шукає лише перший збіг, тобто першу цифру `pattern:\d`.
2222

23-
Let's add the `pattern:g` flag to find all digits:
23+
Давайте додамо прапор `pattern:g`, щоб знайти всі цифри:
2424

2525
```js run
26-
let str = "+7(903)-123-45-67";
26+
let str = "+1(703)-123-45-67";
2727

2828
let regexp = /\d/g;
2929

30-
alert( str.match(regexp) ); // array of matches: 7,9,0,3,1,2,3,4,5,6,7
30+
alert( str.match(regexp) ); // масив збігів: 1,7,0,3,1,2,3,4,5,6,7
3131

32-
// let's make the digits-only phone number of them:
33-
alert( str.match(regexp).join('') ); // 79031234567
32+
// давайте зробимо з них номер телефону лише з цифр:
33+
alert( str.match(regexp).join('') ); // 17031234567
3434
```
3535

36-
That was a character class for digits. There are other character classes as well.
36+
Це був символьний клас для цифр. Є й інші символьні класи.
3737

38-
Most used are:
38+
Найбільш використовувані:
3939

40-
`pattern:\d` ("d" is from "digit")
41-
: A digit: a character from `0` to `9`.
40+
`pattern:\d` ("d" від англійского "digit" означає "цифра")
41+
: Цифра: символ від `0` до `9`.
4242

43-
`pattern:\s` ("s" is from "space")
44-
: A space symbol: includes spaces, tabs `\t`, newlines `\n` and few other rare characters, such as `\v`, `\f` and `\r`.
43+
`pattern:\s` ("s" від англійского "space" означає "пробіл")
44+
: Пробільні символи: включає символ пробілу, табуляції `\t`, перенесення рядка `\n` і деякі інші рідкісні пробілові символи, що позначаються як `\v`, `\f` і `\r`.
4545

46-
`pattern:\w` ("w" is from "word")
47-
: A "wordly" character: either a letter of Latin alphabet or a digit or an underscore `_`. Non-Latin letters (like cyrillic or hindi) do not belong to `pattern:\w`.
46+
`pattern:\w` ("w" від англійского "word" означає "слово")
47+
: Символ "слова" -- літера латинського алфавіту, цифра або символ підкреслення `_`. Нелатинські літери (наприклад, кирилиця чи хінді) не належать до `pattern:\w`.
4848

49-
For instance, `pattern:\d\s\w` means a "digit" followed by a "space character" followed by a "wordly character", such as `match:1 a`.
49+
Наприклад, `pattern:\d\s\w` означає "цифру", за якою йде "символ пробілу", після якого йде "символ слова", наприклад `match:1 a`.
5050

51-
**A regexp may contain both regular symbols and character classes.**
51+
**Регулярний вираз може містити як звичайні символи, так і символьні класи.**
5252

53-
For instance, `pattern:CSS\d` matches a string `match:CSS` with a digit after it:
53+
Наприклад, `pattern:CSS\d` відповідає рядку `match:CSS` із цифрою після нього:
5454

5555
```js run
56-
let str = "Is there CSS4?";
56+
let str = "Чи існує CSS4?";
5757
let regexp = /CSS\d/
5858

5959
alert( str.match(regexp) ); // CSS4
6060
```
6161

62-
Also we can use many character classes:
62+
Також ми можемо використовувати багато символьних класів:
6363

6464
```js run
6565
alert( "I love HTML5!".match(/\s\w\w\w\w\d/) ); // ' HTML5'
6666
```
6767

68-
The match (each regexp character class has the corresponding result character):
68+
Відповідність (кожному символьному класу відповідає один символ результату):
6969

7070
![](love-html5-classes.svg)
7171

72-
## Inverse classes
72+
## Зворотні символьні класи
7373

74-
For every character class there exists an "inverse class", denoted with the same letter, but uppercased.
74+
Для кожного символьного класу існує "зворотній клас", що позначається тією ж літерою, але у верхньому регістрі.
7575

76-
The "inverse" means that it matches all other characters, for instance:
76+
"Зворотній" означає, що він відповідає всім іншим символам, наприклад:
7777

7878
`pattern:\D`
79-
: Non-digit: any character except `pattern:\d`, for instance a letter.
79+
: Не цифра: будь-який символ, окрім `pattern:\d`, наприклад, літера.
8080

8181
`pattern:\S`
82-
: Non-space: any character except `pattern:\s`, for instance a letter.
82+
: Не пробіл: будь-який символ, окрім `pattern:\s`, наприклад, літера.
8383

8484
`pattern:\W`
85-
: Non-wordly character: anything but `pattern:\w`, e.g a non-latin letter or a space.
85+
: Будь-який символ, окрім `pattern:\w`, тобто не букви з латиниці, не символ підкреслення і цифра.
8686

87-
In the beginning of the chapter we saw how to make a number-only phone number from a string like `subject:+7(903)-123-45-67`: find all digits and join them.
87+
На початку розділу ми бачили, як створити номер телефону з рядка виду `subject:+1(703)-123-45-67`: знайти всі цифри та з'єднати їх.
8888

8989
```js run
90-
let str = "+7(903)-123-45-67";
90+
let str = "+1(703)-123-45-67";
9191

92-
alert( str.match(/\d/g).join('') ); // 79031234567
92+
alert( str.match(/\d/g).join('') ); // 17031234567
9393
```
9494

95-
An alternative, shorter way is to find non-digits `pattern:\D` and remove them from the string:
95+
Альтернативний, коротший шлях -- знайти нецифрові символи `pattern:\D` і видалити їх з рядка:
9696

9797
```js run
98-
let str = "+7(903)-123-45-67";
98+
let str = "+1(703)-123-45-67";
9999

100-
alert( str.replace(/\D/g, "") ); // 79031234567
100+
alert( str.replace(/\D/g, "") ); // 17031234567
101101
```
102102

103-
## A dot is "any character"
103+
## Крапка -- це будь-який символ
104104

105-
A dot `pattern:.` is a special character class that matches "any character except a newline".
105+
Крапка `pattern:.` -- це спеціальний символьний клас, який відповідає "будь-якому символу, крім символу нового рядка".
106106

107-
For instance:
107+
Наприклад:
108108

109109
```js run
110-
alert( "Z".match(/./) ); // Z
110+
alert( "Y".match(/./) ); // Y
111111
```
112112

113-
Or in the middle of a regexp:
113+
Або в середині регулярного виразу:
114114

115115
```js run
116116
let regexp = /CS.4/;
117117

118118
alert( "CSS4".match(regexp) ); // CSS4
119119
alert( "CS-4".match(regexp) ); // CS-4
120-
alert( "CS 4".match(regexp) ); // CS 4 (space is also a character)
120+
alert( "CS 4".match(regexp) ); // CS 4 (пробіл також є символом)
121121
```
122122

123-
Please note that a dot means "any character", but not the "absence of a character". There must be a character to match it:
123+
Зверніть увагу, що точка означає "будь-який символ", але не "відсутність символу". Там має бути будь-який символ, щоб відповідати умові пошуку:
124124

125125
```js run
126-
alert( "CS4".match(/CS.4/) ); // null, no match because there's no character for the dot
126+
alert( "CS4".match(/CS.4/) ); // null, немає збігів тому що немає символу для точки
127127
```
128128

129-
### Dot as literally any character with "s" flag
129+
### Крапка, як буквально будь-який символ із прапорцем "s".
130130

131-
By default, a dot doesn't match the newline character `\n`.
131+
За замовчуванням крапка не відповідає символу нового рядка `\n`.
132132

133-
For instance, the regexp `pattern:A.B` matches `match:A`, and then `match:B` with any character between them, except a newline `\n`:
133+
Наприклад, регулярний вираз `pattern:A.B` відповідає `match:A`, а потім `match:B` з будь-яким символом між ними, крім символу нового рядка `\n`:
134134

135135
```js run
136-
alert( "A\nB".match(/A.B/) ); // null (no match)
136+
alert( "A\nB".match(/A.B/) ); // null (немає збігів)
137137
```
138138

139-
There are many situations when we'd like a dot to mean literally "any character", newline included.
139+
Є багато ситуацій, коли ми хотіли б, щоб крапка означала буквально "будь-який символ", включаючи новий рядок.
140140

141-
That's what flag `pattern:s` does. If a regexp has it, then a dot `pattern:.` matches literally any character:
141+
Ось що робить прапор `pattern:s`. Якщо регулярний вираз містить його, то крапка `pattern:.` відповідає буквально будь-якому символу:
142142

143143
```js run
144-
alert( "A\nB".match(/A.B/s) ); // A\nB (match!)
144+
alert( "A\nB".match(/A.B/s) ); // A\nB (збіг!)
145145
```
146146

147-
````warn header="Not supported in IE"
148-
The `pattern:s` flag is not supported in IE.
147+
````warn header="Не підтримується в IE"
148+
Прапор `pattern:s` не підтримується в IE.
149149
150-
Luckily, there's an alternative, that works everywhere. We can use a regexp like `pattern:[\s\S]` to match "any character" (this pattern will be covered in the article <info:regexp-character-sets-and-ranges>).
150+
На щастя, є альтернатива, яка працює всюди. Ми можемо використовувати регулярний вираз, як-от `pattern:[\s\S]`, щоб знаходити "будь-який символ" (цей шаблон буде описано в статті <info:regexp-character-sets-and-ranges>).
151151
152152
```js run
153-
alert( "A\nB".match(/A[\s\S]B/) ); // A\nB (match!)
153+
alert( "A\nB".match(/A[\s\S]B/) ); // A\nB (збіг!)
154154
```
155155
156-
The pattern `pattern:[\s\S]` literally says: "a space character OR not a space character". In other words, "anything". We could use another pair of complementary classes, such as `pattern:[\d\D]`, that doesn't matter. Or even the `pattern:[^]` -- as it means match any character except nothing.
156+
Шаблон `pattern:[\s\S]` буквально говорить: "пробіл АБО не пробіл". Іншими словами, "що завгодно". Ми могли б використати іншу пару додаткових класів, наприклад `pattern:[\d\D]`, це не має значення. Або навіть `pattern:[^]` -- оскільки це означає збіг будь-якого символу, крім нічого.
157157
158-
Also we can use this trick if we want both kind of "dots" in the same pattern: the actual dot `pattern:.` behaving the regular way ("not including a newline"), and also a way to match "any character" with `pattern:[\s\S]` or alike.
158+
Також ми можемо використати цей прийом, якщо хочемо, щоб обидва типи "крапок" були в одному шаблоні: наявний шаблон `pattern:.` крапки, який поводиться звичайним чином ("без нового рядка"), а також відповідності "будь-якому символу" з `pattern:[\s\S]` або подібним.
159159
````
160160

161-
````warn header="Pay attention to spaces"
162-
Usually we pay little attention to spaces. For us strings `subject:1-5` and `subject:1 - 5` are nearly identical.
161+
````warn header="Зверніть увагу на пробіли"
162+
Зазвичай ми приділяємо мало уваги пробілам. Для нас рядки `subject:1-5` і `subject:1 - 5` майже ідентичні.
163163
164-
But if a regexp doesn't take spaces into account, it may fail to work.
164+
Але якщо регулярний вираз не враховує пробіли, він може не спрацювати.
165165
166-
Let's try to find digits separated by a hyphen:
166+
Спробуємо знайти цифри, розділені дефісом:
167167
168168
```js run
169-
alert( "1 - 5".match(/\d-\d/) ); // null, no match!
169+
alert( "1 - 5".match(/\d-\d/) ); // null, немає збігів!
170170
```
171171
172-
Let's fix it adding spaces into the regexp `pattern:\d - \d`:
172+
Давайте виправимо це, додавши пробіли в регулярний вираз `pattern:\d - \d`:
173173
174174
```js run
175-
alert( "1 - 5".match(/\d - \d/) ); // 1 - 5, now it works
176-
// or we can use \s class:
177-
alert( "1 - 5".match(/\d\s-\s\d/) ); // 1 - 5, also works
175+
alert( "1 - 5".match(/\d - \d/) ); // 1 - 5, тепер працює
176+
// або ми можемо використати \s клас:
177+
alert( "1 - 5".match(/\d\s-\s\d/) ); // 1 - 5, також працює
178178
```
179179
180-
**A space is a character. Equal in importance with any other character.**
180+
**Пробіл -- це символ. Так само важливий, як і будь-який інший.**
181181
182-
We can't add or remove spaces from a regular expression and expect it to work the same.
182+
Ми не можемо додавати або видаляти пробіли в регулярному виразі й сподіватися, що він працюватиме так само.
183183
184-
In other words, in a regular expression all characters matter, spaces too.
184+
Іншими словами, у регулярному виразі всі символи мають значення, пробіли також.
185185
````
186186

187-
## Summary
187+
## Підсумки
188188

189-
There exist following character classes:
189+
Існують такі класи символів:
190190

191-
- `pattern:\d` -- digits.
192-
- `pattern:\D` -- non-digits.
193-
- `pattern:\s` -- space symbols, tabs, newlines.
194-
- `pattern:\S` -- all but `pattern:\s`.
195-
- `pattern:\w` -- Latin letters, digits, underscore `'_'`.
196-
- `pattern:\W` -- all but `pattern:\w`.
197-
- `pattern:.` -- any character if with the regexp `'s'` flag, otherwise any except a newline `\n`.
191+
- `pattern:\d` -- цифри.
192+
- `pattern:\D` -- нецифри.
193+
- `pattern:\s` -- символи пробілів, табуляції, символи нового рядка.
194+
- `pattern:\S` -- усі, крім `pattern:\s`.
195+
- `pattern:\w` -- латинські літери, цифри, підкреслення `'_'`.
196+
- `pattern:\W` -- усі, крім `pattern:\w`.
197+
- `pattern:.` -- будь-який символ, якщо з прапорцем регулярного виразу `'s'`, інакше будь-який, крім символу нового рядка `\n`.
198198

199-
...But that's not all!
199+
...Але це ще не все!
200200

201-
Unicode encoding, used by JavaScript for strings, provides many properties for characters, like: which language the letter belongs to (if it's a letter), is it a punctuation sign, etc.
201+
Кодування Юнікод, яке використовується JavaScript для рядків, надає багато властивостей для символів, наприклад: до якої мови належить літера (якщо це літера), чи це знак пунктуації тощо.
202202

203-
We can search by these properties as well. That requires flag `pattern:u`, covered in the next article.
203+
Ми також можемо шукати за цими властивостями. Для цього потрібен прапорець `pattern:u`, який описано в наступній статті.

0 commit comments

Comments
 (0)