Learn the basics of regular expressions

韦小宝
Release: 2023-03-21 11:46:02
Original
1306 people have browsed it

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. Related concepts of regular expressions

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!