Skip to content

Commit 0c6ecae

Browse files
committed
Trenslate 9-regular-expressions_03-regexp-character-classes_article.md_ru #50
1 parent 61b57df commit 0c6ecae

1 file changed

Lines changed: 47 additions & 46 deletions

File tree

  • 9-regular-expressions/03-regexp-character-classes

9-regular-expressions/03-regexp-character-classes/article.md

Lines changed: 47 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
# Character classes
1+
# Классы символов
22

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`.
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 a "digit" class. It's written as `\d`. We put it in the pattern, that means "any single digit".
9+
Для начала давайте рассмотрим класс "цифр". Он обозначается как `\d`. Мы помещаем это обозначение в регулярное выражение, что соответствует "любой одной цифре".
1010

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

1313
```js run
1414
let str = "+7(903)-123-45-67";
@@ -18,99 +18,100 @@ let reg = /\d/;
1818
alert( str.match(reg) ); // 7
1919
```
2020

21-
Without the flag `g`, the regular expression only looks for the first match, that is the first digit `\d`.
21+
Без флага `g` регулярное выражение ищет только первое совпадение, то есть первую цифру `\ d`.
2222

23-
Let's add the `g` flag to find all digits:
23+
Давайте добавим флаг `g`, чтобы найти все цифры:
2424

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

2828
let reg = /\d/g;
2929

30-
alert( str.match(reg) ); // array of matches: 7,9,0,3,1,2,3,4,5,6,7
30+
alert( str.match(reg) ); // массив совпадений: 7,9,0,3,1,2,3,4,5,6,7
3131

3232
alert( str.match(reg).join('') ); // 79035419441
3333
```
3434

35-
That was a character class for digits. There are other character classes as well.
35+
Это был класс символов для цифр. Есть и другие подобные классы.
3636

37-
Most used are:
37+
Наиболее используемые:
3838

39-
`\d` ("d" is from "digit")
40-
: A digit: a character from `0` to `9`.
39+
`\d` ("d": от английского "digit" – "цифра")
40+
: Цифра: символ от `0` до `9`.
4141

42-
`\s` ("s" is from "space")
43-
: A space symbol: that includes spaces, tabs, newlines.
42+
`\s` ("s": от английского "space" – "пробел")
43+
: Символ пробела: включает пробелы, символы табуляции, переводы строк.
4444

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`, то есть русская буква не подходит.
4747

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"`.
4949

50-
**A regexp may contain both regular symbols and character classes.**
50+
**Регулярное выражение может содержать как обычные символы, так и классы символов.**
5151

52-
For instance, `pattern:CSS\d` matches a string `match:CSS` with a digit after it:
52+
Например, `pattern:CSS\d` соответствует строке` match:CSS` с цифрой после нее:
5353

5454
```js run
55-
let str = "CSS4 is cool";
55+
let str = "Стандарт CSS4 - это здорово";
5656
let reg = /CSS\d/
5757

5858
alert( str.match(reg) ); // CSS4
5959
```
6060

61-
Also we can use many character classes:
61+
Также мы можем использовать несколько классов символов одновременно:
6262

6363
```js run
64-
alert( "I love HTML5!".match(/\s\w\w\w\w\d/) ); // 'HTML5'
64+
alert( "Я люблю HTML5!".match(/\s\w\w\w\w\d/) ); // 'HTML5'
6565
```
6666

67-
The match (each character class corresponds to one result character):
67+
Соответствие (каждому классу символов соответствует один символ результата):
6868

6969
![](love-html5-classes.png)
7070

71-
## Word boundary: \b
71+
## Граница слова: \b
7272

73-
A word boundary `pattern:\b` -- is a special character class.
73+
Граница слова `pattern:\b` - это специальный символьный класс.
7474

75-
It does not denote a character, but rather a boundary between characters.
75+
Он обозначает не какой-то конкретный символ, а границу между символами.
7676

77-
For instance, `pattern:\bJava\b` matches `match:Java` in the string `subject:Hello, Java!`, but not in the script `subject:Hello, JavaScript!`.
77+
Например, `pattern:\bJava\b` соответствует` match:Java` в строке `subject:Hello,Java!`, но не в сценарии `subject: Hello, JavaScript!`.
7878

7979
```js run
80-
alert( "Hello, Java!".match(/\bJava\b/) ); // Java
81-
alert( "Hello, JavaScript!".match(/\bJava\b/) ); // null
80+
alert( "Привет, Java!".match(/\bJava\b/) ); // Java
81+
alert( "Привет, JavaScript!".match(/\bJava\b/) ); // null
8282
```
8383

84-
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+
Граница имеет "нулевую ширину" в том смысле, что обычно класс символов означает символ в результате (например, символ или цифру), но не в этом случае.
8585

86-
The boundary is a test.
86+
Граница – это проверка.
8787

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+
Когда механизм регулярных выражений выполняет поиск, он перемещается по строке в попытке найти совпадение. В каждой позиции строки он пытается найти шаблон.
8989

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`, он проверяет, что позиция в строке является границей слова, то есть одним из трех вариантов:
9191

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`.
9595

96-
For instance, in the string `subject:Hello, Java!` the following positions match `\b`:
96+
Например, в строке `subject:Привет, Java!` Следующие позиции соответствуют `\b`:
9797

9898
![](hello-java-boundaries.png)
9999

100-
So it matches `pattern:\bHello\b`, because:
100+
Так что это соответствует `pattern:\bПривет\b`, потому что:
101101

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` снова совпадает, так как мы находимся между `т` и пробелом.
105105

106106
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` (потому что восклицательный знак не является словесным символом, поэтому после него нет границы слова).
107108

108109

109110
```js run
110-
alert( "Hello, Java!".match(/\bHello\b/) ); // Hello
111-
alert( "Hello, Java!".match(/\bJava\b/) ); // Java
112-
alert( "Hello, Java!".match(/\bHell\b/) ); // null (no match)
113-
alert( "Hello, Java!".match(/\bJava!\b/) ); // null (no match)
111+
alert( "Привет, Java!".match(/\bПривет\b/) ); // Привет
112+
alert( "Привет, Java!".match(/\bJava\b/) ); // Java
113+
alert( "Привет, Java!".match(/\bПривед\b/) ); // null (no match)
114+
alert( "Привет, Java!".match(/\bJava!\b/) ); // null (no match)
114115
```
115116

116117
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

Comments
 (0)