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:

-
^ matches the start position of the input string.
-
[0-9]+matches multiple digits, [0-9] matches a single digit,+ matches one or more.
-
abc$matches a letter abc and ends with abc at the end,$ matches the end position of the input string.
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}$

^matches the beginning of the string.[a-zA-Z0-9_-]represents a character set containing lowercase letters, uppercase letters, digits, underscores, and the hyphen -.{3,15}indicates the preceding character set appears at least 3 times and at most 15 times, thus limiting the username length to between 3 and 15 characters.$matches the end of the string.
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
- Ordinary characters: ordinary characters match literally; for example, matching the letter "a" will match the "a" character in the text.
- Metacharacters: metacharacters have special meanings, for example
\dmatches any digit character,\wmatches any alphanumeric character,.matches any character (except newline), etc.
Quantifier
*: matches the preceding pattern zero or more times.+: matches the preceding pattern one or more times.?: matches the preceding pattern zero or one time.{n}: matches the preceding pattern exactly n times.{n,}: matches the preceding pattern at least n times.{n,m}: matches the preceding pattern at least n times and at most m times.
Character class
[ ]: matches any one character inside the parentheses. For example,[abc]matches the character "a", "b", or "c".[^ ]: matches any character except those inside the parentheses. For example,[^abc]matches any character except "a", "b", or "c".
Boundary matching
^: matches the start of a string.$: matches the end of a string.\b: matches a word boundary.\B: matches a non-word boundary.
Grouping and capturing
( ): used for grouping and capturing subexpressions.(?: ): used for grouping but not capturing subexpressions.
Special characters
\: an escape character, used to match the special character itself..: matches any character (except newline).|: used to specify a choice among multiple patterns.
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:
- 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.
- 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-DDto uniformlyMM/DD/YYYY. - 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.
- Validate email address: check whether the input looks like
username@domain.com. - Validate phone number: check whether it conforms to the country/region's phone number format (such as China's 11-digit number).
- Validate password strength: require the password to contain uppercase and lowercase letters, digits, and special characters.
- Validate date format: ensure the date is
2023-12-25or12/25/2023And other valid formats. - Validate ID card numbers: Matches ID card numbers that follow specific encoding rules.
2. Text Search and Filtering
Quickly locate information within large amounts of text.
- Log analysis: Search the server logs for all entries at
ERRORorWARNthe level. - Code Search: In an IDE or editor, use a regular expression to search for all function definitions (such as
function xxx(...)) or specific variable names. - Find Content in Documents: Find all phone numbers or URLs appearing in a long document.
3. Text Replacement and Cleaning
Batch-modify text content to normalize it.
- Format Data: Convert phone numbers from
12345678901to the format123-4567-8901. - Clean Data: Remove redundant whitespace characters from text (such as multiple consecutive spaces or tabs).
- Sensitive Information Masking: Replace ID card numbers in text with
***, such as110101199001011234->110101********1234. - Code Refactoring: Batch rename variables or function names.
4. Text Extraction and Parsing
Extract structured data from unstructured text.
- Web Crawler: Extract all links ( from HTML code
href="...") or image addresses (src="..."). - Parse Configuration Files: Read
key = valueconfiguration files in the format. - Extract Specific Data: Extract all monetary amounts appearing in a passage of text (such as
¥100.50or$99.99).
5. String Splitting
Use complex rules, not just single characters, to split strings.
- Use one or more spaces, commas, or semicolons to split a sentence.
- According to different delimiters (such as
,,;,\t) to parse CSV or TSV data.
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:
-
1951: One of the founders of computation theory, American computer scientist Stephen Kleene, first proposed the concept of regular languages and used formal methods to describe such languages. This laid the theoretical foundation for the development of regular expressions.
-
1960s: Ken Thompson, one of the co-creators of the Unix operating system, developed the first program to practically apply regular expressions, which was part of the grep command in Unix. This marked the practical application of regular expressions.
-
1970s: Ken Thompson and Rob Pike developed the first regular expression engine, widely used in Unix systems, which played a key role in popularizing regular expressions.
-
1986: Philip Hazel developed the PCRE (Perl Compatible Regular Expressions) library, a regular expression library that allows Perl-style regular expressions to be used in different programming languages.
-
1997: IEEE released the POSIX.2 standard, which included standard specifications for regular expressions, making their behavior more consistent across different Unix systems.
-
After the 2000s: Regular expressions became increasingly popular in computer programming and text processing, and programming languages and tools supporting them became more abundant and powerful, such as Perl, Python, Java, and JavaScript.
-
Present: Regular expressions remain an important tool for text processing and data extraction, widely used in data science, text analysis, web crawling, string search and replacement, and other fields.
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+/ |