0Pricing
Linux Command Line Mastery · Урок

Освоение регулярных выражений (Regex)

Разберитесь в синтаксисе и возможностях регулярных выражений для расширенного сопоставления с шаблонами.

«Освоение регулярных выражений (Regex)» — бесплатный урок Linux Command Line Mastery на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Linux Command Line Mastery, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Linux Command Line Mastery содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Intro to Regular Expressions

Welcome to Regular Expressions (Regex)! Regex is a powerful mini-language used for pattern matching in text. It's like a super-charged search tool.

You can use Regex to search, replace, and validate specific text patterns in files or command output. Mastering it will make you much more efficient at the command line!

Matching Exact Text

The simplest Regex matches literal characters. This means the pattern will look for the exact sequence of characters you provide.

For example, searching for apple will only find occurrences of "apple".

echo "I have an apple and a pineapple." | grep 'apple'

Any Single Character: The Dot (.)

The dot (.) is a special character, called a "metacharacter". It matches any single character, except for a newline. Use it when you don't care what character is in a specific spot.

echo "cat, cot, cut, c@t" | grep 'c.t'

Matching Repetition: Quantifiers

Quantifiers let you specify how many times a character or group should appear. These are powerful for flexible matching:

  • *: Matches zero or more occurrences.
  • +: Matches one or more occurrences.
  • ?: Matches zero or one occurrence (makes it optional).
echo "color colour coor" | grep 'colou*r'

Specific Choices: Character Classes

Use square brackets ([]) to match any one character from a specified set. This defines specific options for a single position in your pattern.

For example, [aeiou] would match any single vowel.

echo "grey gray" | grep 'gr[ae]y'

Defining Ranges in Classes

Inside character classes, you can specify ranges of characters using a hyphen (-). This makes your patterns much shorter and easier to read.

  • [0-9]: Matches any digit.
  • [a-z]: Matches any lowercase letter.
  • [A-Z]: Matches any uppercase letter.
  • [a-zA-Z]: Matches any letter (case-insensitive).
echo "num1 num2 numA" | grep 'num[0-9]'

Excluding Characters: Negation

To match any character that is NOT in a specified set, place a caret (^) as the first character inside the square brackets ([^...]).

echo "apple, banana, 123, !@#" | grep '[^a-z]'

Start and End: Anchors

Anchors don't match characters; they match positions. They "anchor" your pattern to the start or end of a line.

  • ^: Matches the beginning of a line.
  • $: Matches the end of a line.

Note: When ^ is used outside of [], it's an anchor, not a negation!

echo -e "start here\n here end\nstart and end" | grep '^start'

Putting It All Together

Let's combine some of these concepts. Imagine you want to find lines that start with a capital letter, followed by any number of lowercase letters, and end with a digit.

echo -e "Hello1\nworld2\nAnotherTest3" | grep '^[A-Z][a-z]*[0-9]$'

Regex Challenge

Consider the following text:

apple apples apply app Apple

Which regular expression would match "apple" and "apples", but NOT "apply", "app", or "Apple"?

Recap: Regex Fundamentals

In this lesson, you've taken your first steps into the powerful world of Regular Expressions! We covered:

  • Literal matching for exact text.
  • The . metacharacter for any single character.
  • Quantifiers (*, +, ?) for repetition.
  • Character classes ([]) and ranges ([a-z]) for specific sets.
  • Negation ([^]) to exclude characters.
  • Anchors (^, $) for start and end of lines.

These are the building blocks for creating sophisticated text patterns. Keep practicing!

Часто задаваемые вопросы

Урок «Освоение регулярных выражений (Regex)» бесплатный?

Да — полный текст урока «Освоение регулярных выражений (Regex)» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Linux Command Line Mastery, подпишись на CoddyKit PRO. Курс Linux Command Line Mastery содержит 4 уроков всего.

Чему я научусь в уроке «Освоение регулярных выражений (Regex)»?

Разберитесь в синтаксисе и возможностях регулярных выражений для расширенного сопоставления с шаблонами. Ты практикуешь Linux Command Line Mastery с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Linux Command Line Mastery?

Предыдущий опыт не требуется. Linux Command Line Mastery на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.

Сколько времени занимает урок «Освоение регулярных выражений (Regex)»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Linux Command Line Mastery?

Да. Каждый урок Linux Command Line Mastery включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Освоение регулярных выражений (Regex)
  2. Расширенные шаблоны `grep` и `find`
  3. `xargs` для объединения команд
  4. Масштабное редактирование потоков с sed и tr
← Назад к Linux Command Line Mastery