Basics of Regex

Basics of Regex

What is Regex?

Regular expressions (Regex) are sequences of characters that define a search pattern. They are used for string matching and manipulation. Regex is a powerful tool for tasks such as form validation, search and replace operations, and data extraction.

Basic Syntax and Structure

A regular expression is a pattern enclosed in forward slashes (/). Here is an example of a simple regular expression:

javascript
	const regex = /hello/;

In this example, /hello/ is a regular expression that matches the exact string “hello”.

Common Metacharacters

Metacharacters are special characters in Regex that have specific meanings. Here are some of the most commonly used metacharacters:

  • . : Matches any single character except newline
  • ^ : Matches the start of a string
  • $ : Matches the end of a string
  • * : Matches 0 or more occurrences of the preceding element
  • + : Matches 1 or more occurrences of the preceding element
  • ? : Matches 0 or 1 occurrence of the preceding element
  • \ : Escapes a metacharacter to match it literally

Example: Matching a Simple Pattern

Let’s look at an example that uses some of these metacharacters:

javascript
	const regex = /^h.llo$/;
	const str1 = 'hello';
	const str2 = 'hallo';
	const str3 = 'hullo';
	
	console.log(regex.test(str1)); // true
	console.log(regex.test(str2)); // true
	console.log(regex.test(str3)); // true
	console.log(regex.test('heello')); // false
	console.log(regex.test('hello!')); // false

In this example:

  • ^ ensures the match starts at the beginning of the string.
  • . matches any single character.
  • llo is the literal string we expect to follow.
  • $ ensures the match ends at the end of the string.

This pattern will match any string that starts with ‘h’, followed by any character, and then ‘llo’.

Exercises

  1. Write a regular expression that matches the word “world” at the end of a string.
  2. Create a Regex pattern that matches any string containing “abc” followed by any single character and then “def”.

By understanding the basics of Regex, you can start to build more complex patterns for various text processing tasks.