Back to Blog
Regular Expressions

Regular Expressions Basics: Master Text Matching from Scratch

E
EfficTools Team
December 8, 202416 min read

Regular Expressions Basics: Master Text Matching from Scratch

What are Regular Expressions?

Regular expressions (Regex) are tools for describing string matching patterns. They can be used to:

  • Validate input formats (email, phone numbers, etc.)
  • Search and replace text
  • Extract specific information
  • Data cleaning and processing

Basic Syntax

Literal Characters

The simplest regular expressions are ordinary characters that match themselves:

``

hello matches "hello"

123 matches "123"

`

Special Characters (Metacharacters)

CharacterMeaning
.Match any single character
^Match start of string
$Match end of string
Match preceding character 0 or more times
+Match preceding character 1 or more times
?Match preceding character 0 or 1 time
\Escape special characters

Character Classes

`

[abc] Match a, b, or c

[a-z] Match any lowercase letter

[0-9] Match any digit

[^abc] Match any character except a, b, or c

`

Predefined Character Classes

`

\d Match digits, equivalent to [0-9]

\D Match non-digits

\w Match word characters (letters, digits, underscore)

\W Match non-word characters

\s Match whitespace characters

\S Match non-whitespace characters

`

Quantifiers

`

{n} Match exactly n times

{n,} Match at least n times

{n,m} Match n to m times

`

Grouping and Capturing

Use parentheses () to create capture groups:

`

(abc)+ Match one or more "abc"

(\d{4})-(\d{2})-(\d{2}) Match date format

`

Common Regular Expression Examples

Email Validation

`

^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$

`

Phone Number Validation (China)

`

^1[3-9]\d{9}$

`

URL Matching

`

https?:\/\/[\w\-]+(\.[\w\-]+)+[\w\-.,@?^=%&:/~+#]

`

Chinese Characters

`

[\u4e00-\u9fa5]+

`

Using Regular Expressions in JavaScript

`javascript

// Create regular expression

const regex = /hello/i; // i means case-insensitive

// Test match

regex.test('Hello World'); // true

// Search match

'Hello World'.match(/\w+/g); // ['Hello', 'World']

// Replace

'Hello World'.replace(/World/, 'Regex'); // 'Hello Regex'

``

Using EfficTools to Test Regular Expressions

The best way to learn regular expressions is through practice. Using our Regular Expression Testing Tool, you can:

  • Test regular expressions in real-time
  • View highlighted match results
  • View capture group contents
  • Support for multiple flags

Learning Tips

  • Start simple and gradually increase complexity
  • Practice more and test more
  • Use online tools to verify
  • Read others' regular expressions to learn techniques
  • Summary

    Regular expressions are a skill worth investing time in learning. Although they may seem complex at first, once you master the basic syntax, they will become your powerful assistant for text processing.

    Regular ExpressionsRegexTutorialJavaScript
    Share this article