Home Web Front-end JS Tutorial Summary of regular expressions (practical summary)

Summary of regular expressions (practical summary)

Mar 30, 2018 pm 01:42 PM
Actual combat expression

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+)?$/;
Copy after login

of valid digits 2)

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

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

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

 var reg = /^[\u4e00-\u9fa5]{2,4}$/;
Copy after login
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)
Copy after login

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 of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP Practical: Code Example to Quickly Implement Fibonacci Sequence PHP Practical: Code Example to Quickly Implement Fibonacci Sequence Mar 20, 2024 pm 02:24 PM

PHP Practice: Code Example to Quickly Implement the Fibonacci Sequence The Fibonacci Sequence is a very interesting and common sequence in mathematics. It is defined as follows: the first and second numbers are 0 and 1, and from the third Starting with numbers, each number is the sum of the previous two numbers. The first few numbers in the Fibonacci sequence are 0,1,1.2,3,5,8,13,21,...and so on. In PHP, we can generate the Fibonacci sequence through recursion and iteration. Below we will show these two

Teach you step by step how to subcontract uniapp and mini programs (pictures and text) Teach you step by step how to subcontract uniapp and mini programs (pictures and text) Jul 22, 2022 pm 04:55 PM

This article brings you relevant knowledge about uniapp cross-domain, and introduces issues related to subcontracting of uniapp and mini programs. Each mini program that uses subcontracting must contain a main package. The so-called main package is where the default startup page/TabBar page is placed, and some public resources/JS scripts are required for all sub-packages; while sub-packages are divided according to the developer's configuration. I hope it will be helpful to everyone.

MySQL table design practice: Create an e-commerce order table and product review table MySQL table design practice: Create an e-commerce order table and product review table Jul 03, 2023 am 08:07 AM

MySQL table design practice: Create an e-commerce order table and product review table. In the database of the e-commerce platform, the order table and product review table are two very important tables. This article will introduce how to use MySQL to design and create these two tables, and give code examples. 1. Design and creation of order table The order table is used to store the user's purchase information, including order number, user ID, product ID, purchase quantity, order status and other fields. First, we need to create a table named "order" using CREATET

Java development practice: Integrating Qiniu cloud storage service to achieve file upload Java development practice: Integrating Qiniu cloud storage service to achieve file upload Jul 06, 2023 pm 06:22 PM

Java Development Practice: Integrating Qiniu Cloud Storage Service to Implement File Upload Introduction With the development of cloud computing and cloud storage, more and more applications need to upload files to the cloud for storage and management. The advantages of cloud storage services are high reliability, scalability and flexibility. This article will introduce how to use Java language development, integrate Qiniu cloud storage service, and implement file upload function. About Qiniu Cloud Qiniu Cloud is a leading cloud storage service provider in China, providing comprehensive cloud storage and content distribution services. Users can use Qiniu Yunti

Golang Practical Combat: Sharing of Implementation Tips for Data Export Function Golang Practical Combat: Sharing of Implementation Tips for Data Export Function Feb 29, 2024 am 09:00 AM

The data export function is a very common requirement in actual development, especially in scenarios such as back-end management systems or data report export. This article will take the Golang language as an example to share the implementation skills of the data export function and give specific code examples. 1. Environment preparation Before starting, make sure you have installed the Golang environment and are familiar with the basic syntax and operations of Golang. In addition, in order to implement the data export function, you may need to use a third-party library, such as github.com/360EntSec

In-depth study of Elasticsearch query syntax and practical combat In-depth study of Elasticsearch query syntax and practical combat Oct 03, 2023 am 08:42 AM

In-depth study of Elasticsearch query syntax and practical introduction: Elasticsearch is an open source search engine based on Lucene. It is mainly used for distributed search and analysis. It is widely used in full-text search of large-scale data, log analysis, recommendation systems and other scenarios. When using Elasticsearch for data query, flexible use of query syntax is the key to improving query efficiency. This article will delve into the Elasticsearch query syntax and give it based on actual cases.

Vue practice: date picker component development Vue practice: date picker component development Nov 24, 2023 am 09:03 AM

Vue Practical Combat: Date Picker Component Development Introduction: The date picker is a component often used in daily development. It can easily select dates and provides various configuration options. This article will introduce how to use the Vue framework to develop a simple date picker component and provide specific code examples. 1. Requirements analysis Before starting development, we need to conduct a requirements analysis to clarify the functions and characteristics of the components. According to the common date picker component functions, we need to implement the following function points: Basic functions: able to select dates, and

Become a Go language master: learning path and practical experience sharing Become a Go language master: learning path and practical experience sharing Mar 04, 2024 am 10:12 AM

Become a Go language master: Sharing learning paths and practical experience Go language has been favored by developers since its birth. Its simplicity, efficiency, and outstanding concurrency performance have attracted more and more developers to join the learning and application of Go language. ranks. This article will share a learning path to become a master of the Go language. At the same time, combined with practical experience, we will provide some code examples for your reference. Learning path 1. Learn basic knowledge. No matter when learning any language, the first thing to master is the basic knowledge. The basic knowledge of Go language mainly includes data types,

See all articles