Table of Contents
Regular expressionLearning (continuous updates)" >Regular expressionLearning (continuous updates)
1. What is a regular expression" >1. What is a regular expression
2. Related concepts of regular expressions" >2. Related concepts of regular expressions
3. Simple regular expression" >3. Simple regular expression
4 .Character escape" >4 .Character escape
5. Character class" >5. Character class
6. Branch conditions" >6. Branch conditions
8.Antonym" >8.Antonym
10. Zero-width assertion" >10. Zero-width assertion
11. Negative zero-width assertion" >11. Negative zero-width assertion
When dealing with string matching problems, the usual behavior is to match as many characters as possible. Taking the expression a.*b and the string aabab as an example, aabab will be matched instead of ab. This matching rule is called greedy matching. " > When dealing with string matching problems, the usual behavior is to match as many characters as possible. Taking the expression a.*b and the string aabab as an example, aabab will be matched instead of ab. This matching rule is called greedy matching.
14. Processing options" >14. Processing options
15. Balanced group/recursive matching" >15. Balanced group/recursive matching
Home Backend Development PHP Tutorial Learn the basics of regular expressions

Learn the basics of regular expressions

Mar 14, 2018 pm 12:52 PM
Base regular expression

This article talks about the basics of regular expressions of JavaScript. If you are not familiar with JavaScript regular expressions, you can just come and learn them. It talks about the basics of JavaScript. Regular expressions, for those who are not familiar with them, let’s take a look!

Regular expressionLearning (continuous updates)

Today I learned the RegExp object when I was learning javascript , take the opportunity to learn regular expressions. I have never been exposed to them before, so I take the opportunity to learn them. It is very comfortable.

Reference website: 30-minute introductory tutorial on regular expressionsClick to open the link

1. What is a regular expression

Regular expressions are used to express string matching rules.

2.1Metacharacters

Metacharacters are defined in regular expressions A special symbol added to regular expressions to replace certain rules.

\b represents the beginning or end of a word
. represents except line breaks Any character other than
* represents any number of the character that appears before *, such as a*, which represents any number of a before it (repeat 0 times or multiple times)
##+
means + any number of the characters that appear before , such as a+, means there is any number of a in front (repeated one or more times)
? Repeat 0 or 1 times                                                                                                  Repeat greater than or equal to n times{n, m}Repeat n to m times##\d
represents a number from 0 to 9                                                               
\w
Matches letters or numbers or underscores or Chinese characters                                                                      tab character, Newline characters, Chinese full-width spaces, etc.
## The end of the matching string

3. Simple regular expression

Start directly from the example:

Example 1: When I want to match the word hello, the regular expression written The expression (matching rule) is: hello

This will match all words containing hello. For example: helloworld is also matched, but if you only want to match hello, You need to use the metacharacter \b to separate hello before and after to form a separate word hello. The regular expression should be: \bhello\b

Example 2 : When the hello you are looking for is followed by a world at any character, you should use the metacharacters . and *. The regular expression is \bhello\b.*\world\b

Example 3: When you want to match phone numbers like 021-xxxxxxx, you should use 021-\d\d\d\d\d\d\d, where "021 -" is a simple character that does not represent any special meaning, and the \d used later is a metacharacter. This regular expression can be abbreviated as 021-\d{7}, which means \d is repeated 7 times.

Example 4: Match 1 or more consecutive numbers, \d+

Example 5: Match words starting with a, \ba \w*\b

Example 6: Match 5-12 digit QQ number, ^\d{5, 12}&

4 .Character escape

If the string you want to find contains metacharacters, you need to add \ in front of the metacharacters to convert the metacharacters into ordinary characters.

5. Character class

The problem solved in this part is what to do if the characters you want to match do not have corresponding metacharacters, then we need to manually Create a character class.

For example, if the numbers 0-9 do not have a \d match, then when we want to find any number from 0-9, we can create a [0-9] character class, which has the same function as \ d are exactly the same.

For example, the regular expression \(?0\d{2}[), -]?\d{8} can be used to match phone numbers. Let’s explain in turn \( represents the pair (Escape, ? means it is repeated 0 or 1 times, \d means two numbers, [), -] means the character class of) and - ,? means it repeats 0 or 1 times, followed by 8 numbers.

6. Branch conditions

What is written above \(?0\d{2}[), -]?\d{ 8} Such a regular expression may match incorrect strings such as (01012345678 or (010-12345678). For such cases, branch conditions can be used. The branch conditions are similar to the logical or || in js, and both It is a short-circuit operator, which ends when a condition can be judged from left to right. For the above situation, it can be written as \(0\d{ 2}\)\d{8}|0\d{2}-\d{8}|\(0\d{2}\)\d{8}

7. Grouping

## This part is to solve the problem of repeating not a single character, but multiple characters. When repeating a single character, we can use the qualifier in the character + metacharacter. Writing method, but when there are multiple repeated characters, you can add () in addition to the repeated characters. For example, the following regular expression can be used to represent the ip address.

#(2[ 0-4]\d|25[0-5]|[01]\d\d?\.){3}(2[0-4]\d|25[0-5]|[01]?\ d\d?)

8.Antonym

When you need to find characters that do not belong to a simple definition, such as characters other than xxx, you need to use it Antonym

##^
# &
##\W\D Matches any character that is not a digit \B Matches any character that is not the beginning or end of a word The characters at position \S match any character that is not whitespace [^x]Match characters other than x[^aeiou]Match characters other than aeiou
Matches any characters that are not letters, numbers, underscores, or Chinese characters

For example, the regular expression ^\S+& is used to match a string of characters that does not contain whitespace charactersString

9. Back reference

The content of this part matches the previous grouping. When we use () to group characters, we can use this grouping by numbering The method will be quoted later. For grouping by (), grouping starts from 1 in the order of ( (). For example, the regular expression \b(\w+)\s+\1\b can be used to match repeated words. , such as go go, etc. Here, the group that appeared before is referenced through \1

## Other involved back reference syntax is:

(exp)
Match exp and capture the current content into automatic groupings name>exp) Match exp, and capture the current content and assign the group name name
(?:exp) Match exp, do not assign the captured content group name

10. Zero-width assertion

is used to find the part before or after a certain part of content but does not include the content.

Regular expression (?=exp) means to assert that the part that appears later can match the expression exp. For example, \b\w+(?=ing\b) matches the front part of words ending in ing. For example, when searching for I'm dancing and singing, dance and singing will be matched (because there is \w+, it will not be matched as s).

Regular expression (?<=exp) means to assert that the previous part can match the expression exp. For example, (?<=\bre)\w+\b will match the second half of the word starting with re. For example, when searching for reading, ading will be matched.

If you want to add a comma to every three digits of a very long number, such as adding a comma to 123456789, you can use the regular expression ((?<=\d)\d {3})+\b, the search result is 234567890 (I don’t understand this part of the search rules...)

The following example uses two assertions at the same time (?=<\ s)\d+(?=\s), used to match numbers between two blank characters, excluding blank characters.

Generally speaking, the purpose of zero-width assertion is to determine the starting point or ending point of matching characters according to certain rules.

11. Negative zero-width assertion

As mentioned earlier, use antonyms to find characters that are not a certain character or are not in a certain character. characters.

For example, if you want to find a word where the letter q appears but is not followed by u. You might write \bq[^u]\w*\b. But for such an expression, an error will occur when q appears at the end of a word, because [^u] will match the separator character of the word, which will then match the next word, which will match characters such as Iraq fighting. string.

In order to solve the antonym occupancy problem, we can use a negative zero-width assertion, because it only matches one position and does not consume any characters. The above expression can be written as \bq(?!u)\w*\b.

## Similarly, we use (?

## A more complex example: (?<=<(\w+)>).*(?=<\/\1> )

When you see the previous (?<=) and the following (?=), you know that both the front and back are zero-width assertions, and <( \w+)> represents the html tag. If the previous one is , the following zero-width assertion means (escaping and backreferences are used). So this regex is to match the parts between html tags.

12. Comments

Include comments through the syntax (?#comment), For example, 2[0-4]\d(?#200-249).

13. Greed and laziness

When dealing with string matching problems, the usual behavior is to match as many characters as possible. Taking the expression a.*b and the string aabab as an example, aabab will be matched instead of ab. This matching rule is called greedy matching.

Sometimes, we need to match lazy matching with as few characters as possible. At this time, do we need to add it after the qualifier mentioned above? , such as a.*?b will convert greedy matching into lazy matching. At this time, aab (characters 1-3) and ab (characters 4-5) will be matched (the specific reason involves the matching rules of regular expressions) .

14. Processing options

Similar to the flag in js, there are case insensitivity, multi-line mode, global mode, etc.

15. Balanced group/recursive matching

This part is to deal with the matching problem, for example, if you want to match the mathematical expression (5*3))) (5*3) cannot simply be written as \(.*\), as this will match the entire expression. Then the matching strategy that should be adopted is similar to the bracket matching problem we have learned. Use the stack to solve it. When encountering (pressing the stack, encountering) popping the stack, if the last stack is empty, this means that the brackets in the expression completely match. If If not empty, the regex engine will backtrack to make the brackets match.

Related recommendations:

How to use regular expressions in JS


The above is the detailed content of Learn the basics of regular expressions. 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

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 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)

How to replace a string starting with something with php regular expression How to replace a string starting with something with php regular expression Mar 24, 2023 pm 02:57 PM

PHP regular expressions are a powerful tool for text processing and conversion. It can effectively manage text information by parsing text content and replacing or intercepting it according to specific patterns. Among them, a common application of regular expressions is to replace strings starting with specific characters. We will explain this as follows

How to match multiple words or strings using Golang regular expression? How to match multiple words or strings using Golang regular expression? May 31, 2024 am 10:32 AM

Golang regular expressions use the pipe character | to match multiple words or strings, separating each option as a logical OR expression. For example: matches "fox" or "dog": fox|dog matches "quick", "brown" or "lazy": (quick|brown|lazy) matches "Go", "Python" or "Java": Go|Python |Java matches words or 4-digit zip codes: ([a-zA

PHP Basics Tutorial: From Beginner to Master PHP Basics Tutorial: From Beginner to Master Jun 18, 2023 am 09:43 AM

PHP is a widely used open source server-side scripting language that can handle all tasks in web development. PHP is widely used in web development, especially for its excellent performance in dynamic data processing, so it is loved and used by many developers. In this article, we will explain the basics of PHP step by step to help beginners from getting started to becoming proficient. 1. Basic syntax PHP is an interpreted language whose code is similar to HTML, CSS and JavaScript. Every PHP statement ends with a semicolon; Note

How to use regular matching to remove html tags in php How to use regular matching to remove html tags in php Mar 21, 2023 pm 05:17 PM

In this article, we will learn how to remove HTML tags and extract plain text content from HTML strings using PHP regular expressions. To demonstrate how to remove HTML tags, let's first define a string containing HTML tags.

How to use regular expressions to remove Chinese characters in php How to use regular expressions to remove Chinese characters in php Mar 03, 2023 am 10:12 AM

How to remove Chinese in PHP using regular expressions: 1. Create a PHP sample file; 2. Define a string containing Chinese and English; 3. Use "preg_replace('/([\x80-\xff]*)/i', '',$a);" The regular method can remove Chinese characters from the query results.

How to verify if a URL is HTTPS protocol using PHP regex How to verify if a URL is HTTPS protocol using PHP regex Jun 24, 2023 am 08:16 AM

Website security has attracted more and more attention, and using the HTTPS protocol to ensure the security of data transmission has become an important part of current website development. In PHP development, how to use regular expressions to verify whether the URL is HTTPS protocol? here we come to find out. Regular expression Regular expression is an expression used to describe rules. It is a powerful tool for processing text and is widely used in text matching, search and replacement. In PHP development, we can use regular expressions to match http in the URL

Sharing tips on using PHP regular expressions to implement Chinese replacement function Sharing tips on using PHP regular expressions to implement Chinese replacement function Mar 24, 2024 pm 05:57 PM

Sharing tips on using PHP regular expressions to implement the Chinese replacement function. In web development, we often encounter situations where Chinese content needs to be replaced. As a popular server-side scripting language, PHP provides powerful regular expression functions, which can easily realize Chinese replacement. This article will share some techniques for using regular expressions to implement Chinese substitution in PHP, and provide specific code examples. 1. Use the preg_replace function to implement Chinese replacement. The preg_replace function in PHP can be used

How to solve Python expression syntax errors? How to solve Python expression syntax errors? Jun 24, 2023 pm 05:04 PM

Python, as a high-level programming language, is easy to learn and use. Once you need to write a Python program, you will inevitably encounter syntax errors, and expression syntax errors are a common one. In this article, we will discuss how to resolve expression syntax errors in Python. Expression syntax errors are one of the most common errors in Python, and they are usually caused by incorrect usage of syntax or missing necessary components. In Python, expressions usually consist of numbers, strings, variables, and operators. most common

See all articles