Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Regular Expression - Introduction

Regular Expression - Introduction

A regular expression (Regular Expression, abbreviated regex or regexp) is a powerful text-processing tool that uses a special string to describe and match a series of strings conforming to a certain syntactic rule.

You can think of it as a super wildcard, an ordinary wildcard (such as * representing any character) has limited functionality, whereas a regular expression can define extremely complex and precise text patterns, from simple word matching to complex structured data extraction, capable of everything.

For example, you have likely used the ? and * wildcards to find files on your hard drive. The ? wildcard matches 0 or 1 character in a filename, while the * wildcard matches zero or more characters. A pattern like data(\w)?.dat will find the following files:

Example

data.

dat

data1.

dat

data2.

dat

datax.

dat

dataN.

dat

Try it »

Using the * character instead of the ? character increases the number of files found. data.*.dat matches all the following files:

Example

data.

dat

data1.

dat

data2.

dat

data12.

dat

datax.

dat

dataXYZ.

dat

Try it »

Although this search method is useful, it is still limited. By understanding how the * wildcard works, we introduce the concepts that regular expressions rely on, but regular expressions are more powerful and flexible.

Using regular expressions can achieve powerful functions through simple means. First, here is a simple example:

When writing a user registration form, we only allow usernames to containcharacters, digits, underscores, and hyphen characters -, and set the length of the username, we can use the following regular expression to define it.

^[a-zA-Z0-9_-]{3,15}$

The above regular expression can match runoob, runoob1. run-oob, run_oob, but does not match ru, because it contains too few letters (less than 3), so it cannot match. It also does not match runoob$, because it contains special characters.

Example

Try it »

Example

Match a string that starts with a digit and ends with abc.

var

str

=

"

123abc

"

;

var

patt1

= /^

[

0

9

]

abc

$/;

document

.

write

(

str

.

match

(

patt1

)

)

;

The text marked below is the expression that obtains the match:

123abc

Try it »


Regex metacharacters and features

Character matching

Quantifier

Character class

Boundary matching

Grouping and capturing

Special characters


Definition and uses of regular expressions

Technically, a regular expression is a string composed of ordinary characters (such as the letters a to z) and special characters (called metacharacters), and this string forms a search pattern, which is used to perform search, match, replace, or split operations in text.

Main Use

Regular expressions mainly have three major uses:

  1. Text search and matching: quickly determine whether a piece of text contains a substring that matches a specific pattern. For example, check whether a string is in a valid email address format.
  2. Text replacement: replace all parts of the text that match a specific pattern with new content. For example, convert all date formats in a document from YYYY-MM-DD to uniformly MM/DD/YYYY.
  3. Text extraction and splitting: precisely extract the parts we care about from a large block of text, or split the text into an array based on a specific delimiter. For example, extract all IP addresses from a log file, or split a CSV string with commas.

Application scenarios of regular expressions

Regular expressions permeate almost every aspect of programming and daily text processing. Here are some of the most common application scenarios:

1. Data validation

This is one of the most classic applications of regular expressions, ensuring that user-input data conforms to the expected format.

2. Text Search and Filtering

Quickly locate information within large amounts of text.

3. Text Replacement and Cleaning

Batch-modify text content to normalize it.

4. Text Extraction and Parsing

Extract structured data from unstructured text.

5. String Splitting

Use complex rules, not just single characters, to split strings.

The following flowchart summarizes the core workflow of regular expressions in data processing:


Development History

The ancestry of regular expressions can be traced back to early research on how the human nervous system works. Two neurophysiologists, Warren McCulloch and Walter Pitts, developed a mathematical way to describe these neural networks.

In 1951, a mathematician named Stephen Kleene, building on the early work of McCulloch and Pitts, published a paper titled "Representation of Neural Network Events" that introduced the concept of regular expressions. Regular expressions are used to describe what he calledthe algebra of regular setsexpressions, and therefore adopted the termRegular expressions.

Later, it was found that this work could be applied to some early research using Ken Thompson's computational search algorithm. Ken Thompson was a principal inventor of Unix. The first practical application of regular expressions was the grep editor in Unix.

The general development history is as follows:


Application Areas

Currently, regular expressions are widely used in many software products, including *nix (Linux, Unix, etc.) and HP operating systems, development environments such as PHP, C#, and Java, as well as many application programs.

C# Regular Expressions

In our C# tutorial,C# Regular Expressions this chapter specifically introduces knowledge about C# regular expressions.

Java Regular Expressions

In our Java tutorial,Java Regular Expressions this chapter specifically introduces knowledge about Java regular expressions.

JavaScript Regular Expressions

In our JavaScript tutorial,JavaScript RegExp Object This chapter specifically introduces knowledge about JavaScript regular expressions, and we also provide a complete JavaScript RegExp Object Reference Manual.

Python Regular Expressions

In our Python basic tutorial,Python Regular Expressions this chapter specifically introduces knowledge about Python regular expressions.

Ruby Regular Expressions

In our Ruby tutorial,Ruby Regular Expressions this chapter specifically introduces knowledge about Ruby regular expressions.

Command or Environment . [ ] ^ $ ( ) { } ? + | ( )
vi √ √ √ √ √
Visual C++ √ √ √ √ √
awk √ √ √ √ awk supports this syntax; you only need to add the --posix or --re-interval parameter on the command line, as seen in the interval expression section of man awk. √ √ √ √
sed √ √ √ √ √ √
delphi √ √ √ √ √ √ √ √ √
python √ √ √ √ √ √ √ √ √ √
java √ √ √ √ √ √ √ √ √ √
javascript √ √ √ √ √ √ √ √ √
php √ √ √ √ √
perl √ √ √ √ √ √ √ √ √
C# √ √ √ √ √ √ √ √

The following is a comparison of regular expression support in mainstream programming languages:

Programming Language Support Method Common Classes/Modules Simple Example (Matching Numbers)
JavaScript Native Language Support RegExp object, or use a literal /.../ /\d+/ or new RegExp("\\d+")
Python Standard library re module re module re.compile(r"\d+")
Java Standard library java.util.regex package Pattern and Matcher class Pattern.compile("\\d+")
PHP Built-in PCRE Functions preg_ a series of functions (such as preg_match) preg_match("/\d+/", $text)
C# System.Text.RegularExpressions Namespacing Regex class new Regex(@"\d+")
Go Standard library regexp package regexp package regexp.MustCompile(\d+)
Ruby Native language support, core class Regexp class /\d+/