search
HomeBackend DevelopmentPHP TutorialLearn the basics of regular expressions

Learn the basics of regular expressions

Mar 14, 2018 pm 12:52 PM
Baseregularexpression

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 (?\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 ((?

The following example uses two assertions at the same time (?=

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: (?).*(?= )

When you see the previous (? 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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)