search
HomeWeb Front-endJS TutorialSummary of regular expressions (practical summary)

This time I will bring you a summary of regular expressions (practical summary), what are the precautions for using regular expressions in practice, the following is a practical case, let’s take a look .

Regular expression is a text pattern composed of ordinary characters (such as characters a to z) and special characters (called metacharacters). The pattern describes one or more strings to be matched when searching for text bodies. Regular expressions serve as a template that matches a character pattern with a searched string.

The editor below summarizes some knowledge points about regular expressions. The specific content is as follows:

1. Metacharacters

[Metacharacters with special meanings]
\d -> matches a number from 0 to 9, equivalent to [0-9], and its opposite is \D -> matches a number except Any character from 0-9
\w -> Matches a number or character from 0-9, a-z, A-Z, _, equivalent to [0-9a-zA-Z_]
\s -> Matches A whitespace character (space, tab...)
\b -> Matches a word boundary
\t -> Matches a tab character
\n -> Matches a newline
. -> Matches any character except \n
^ -> Begins with a certain metacharacter
$ -> Ends with a certain metacharacter
\ -> Transfer Character
x|y -> One of x or y
[xyz] -> Any one of x, y, z
[^xyz] -> Except any one of xyz
[a-z] -> Matches any character in a-z
[^a-z] -> Matches any character except a-z
() -> Grouping in regular expressions

Note:

1) Regarding []

a, [+] ->All characters appearing in square brackets represent their own meaning
b. [12-65] ->This is not 12-65 but one of the three 1/2-6/5

2) About ()

a. The function of grouping is to change the default priority, for example: /^18|19$/, 181, 189, 119, 819, 1819... all match, not 18 or 19 as we think, But changing it to /^(18|19)$/ is simply 18 or 19
b. While capturing the content of the regular match, you can also capture the content of the group match ->Group capture
c. Group reference, for example: /^(\d)(\w)\2\1$/, where \2 is exactly the same as the second group, and \1 is exactly the same as the first group. The content, for example: "0aa0" is consistent with

[quantifier metacharacter representing quantity]

* -> 0 to multiple
+ -> 1 to multiple
? -> 0 to 1
{n} -> appears n times
{n,} -> appears n to multiple times
{n,m} -> appears n to m times

Note:

1) Several situations about ?

a. Place it after the non-quantifier metacharacter to represent the occurrence 0-1 times
b. Place it after the quantifier metacharacter to represent the greediness when canceling the capture, for example: reg=/\d+/; reg.exec("2015") -> "2015" But if the regular Write like this reg=/\d+?/; reg.exec("2015") -> "2"
c. Add ?: at the beginning of the group, which means that the current group only matches and does not capture, for example:/^ (?:\d+)$/
d. Add ?= at the beginning of the group to perform forward search, for example: /^abcdef(?=1|2)$/ Only "abcdef1" and "abcdef2" are consistent
e. Add ?! at the beginning of the group, negative pre-check, for example: /^abcdef(?!1|2)$/ Except "abcdef1" and "abcdef2" do not match, the others as long as it is "abcdef (any things)" are consistent with

[Metacharacters representing their own meaning]

In addition to the above, in the literal mode, any other characters we appear represent their own meaning

var num=12;
var reg=/^\w"+num+"$/; ->Here "+num+" does not splice the value of the variable, and whether it is " or + They are all metacharacters

->For the method that requires splicing strings and variables, we can only use the instance method to create regular expressions

2 and modifiers

i -> ignoreCase ignores the case of letters
g -> global global matching (adding g can solve the laziness during regular capture)
m -> multiline multiline matching

3. Regular rules commonly used in projects

1)

var reg=/^[+-]?(\d|([1-9]\d+))(\.\d+)?$/;

of valid digits 2)

 var reg = /^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
## of the email address # 3) Phone number

 var reg = /^1\d{10}$/;
4) Age between 18-65

 var reg = /^((18|19)|([2-5]\d)|(6[0-5]))$/;
5) Chinese name

 var reg = /^[\u4e00-\u9fa5]{2,4}$/;
6) ID card

 var reg = /^(\d{6})(\d{4})(\d{2})(\d{2})(?:\d{2})(\d)(?:\d|X)$/;
 //-> 12828(省市县) 1990(年) 12(月) 04(日) 06 1(奇数是男偶数是女) 7(数字或者X)

4. Regular matching

reg.test([string]) ->true means successful matching false->unsuccessful matching

5. Regular capture

1)reg.exec([string])

-> First match, the match is successful During capture, an array is returned; if the match is unsuccessful, null is returned;

-> Regular capture is lazy and greedy
-> To solve laziness, add the global modifier g## at the end of the regular expression # -> To solve greediness, add ?

after reading the case in this article. I believe you have mastered the method. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

Detailed explanation of the use of regular pattern modifiers

##What are the new features in regular expressions

The above is the detailed content of Summary of regular expressions (practical summary). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.