image

Regular expressions (RegEx)

A regular expression (RegEx) is a sequence of characters that defines a specific search pattern. Most programming languages include RegEx engines to scan strings for matches, validate user input, or replace substrings.

Computers interpret RegEx patterns by moving a pointer through the target text and comparing it against the defined logic. When the engine finds a sequence that satisfies all the rules in the pattern, it returns a match. This logic relies on a combination of literal characters and special metacharacters that dictate position, quantity, and type.

The example below shows RegEx being used with the ip command and grep command to find strings that look like IPv4 addresses (e.g., 192.168.1.1):

ip addr | grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}"

RegEx Character Classes

Character classes define the set of characters a single position in the string may contain. They narrow the search to specific types, such as digits or letters.

Symbol

Description

.

Matches any character except a newline.

\d

Matches any decimal digit (0-9).

\D

Matches any non-digit character.

\w

Matches any word character (alphanumeric and underscore).

\W

Matches any non-word character.

\s

Matches any whitespace character (space, tab, newline).

\S

Matches any non-whitespace character.

[abc]

Matches any character inside the brackets.

[^abc]

Matches any character NOT inside the brackets.


RegEx Anchors

Anchors match positions within the text. They tie the pattern to the beginning or end of a line or word.

Symbol

Description

^

Matches the start of the string or line.

$

Matches the end of the string or line.

\b

Matches a word boundary.

\B

Matches a position that is not a word boundary.

Tags: Viva Mcq Others