Regular expression (39)

Source: Internet
Author: User
: This article mainly introduces regular expressions (39). For more information about PHP tutorials, see. Introduction to regular expressions:

?? Regular expressions are a syntax rule used to describe character arrangement and matching modes. It is mainly used for string mode segmentation, matching, search and replacement operations. So far, the exact (text) matching we have used earlier is also a regular expression.
?? In PHP, regular expressions are generally a procedural description of a text pattern that consists of regular characters and special characters (similar to wildcards.

?? In PHP, regular expressions have three functions:

?? Matching is often used to extract information from strings.
?? Replace the match text with the new text.
?? Splits a string into a group of smaller information blocks.
?? A regular expression contains at least one atom.

There are two sets of regular expression function libraries in PHP. the two functions are similar, but the execution efficiency is slightly different:

?? One set is provided by the PCRE (Perl Compatible Regular Expression) library. Functions with the prefix "prefix;
?? A set of extensions provided by POSIX (Portable Operating System Interface of Unix. Use a function prefixed with "ereg;
?? One of the reasons for using regular expressions is that in typical search and replacement operations, you can only match the exact text, and it is difficult or even impossible to search for the object's dynamic text.

Regular expression syntax rules

PCRE regular expression:
?? PCRE is called Perl Compatible Regular Expression, which means Perl is Compatible with Regular expressions.
?? PCRE comes from the Perl language, and Perl is one of the most powerful languages for string operations. The initial version of PHP is a product developed by Perl.
?? PCRE syntax supports more features and is more powerful than POSIX syntax. it implements the same function, and the efficiency of using the PCRE library is slightly higher. But they also have many similarities.
?? In PCRE, a pattern expression (that is, a regular expression) is usually included between two backslash "/", such as "/apple /". You only need to place the content of the pattern to be matched between delimiters. The delimiter is not limited to "/". Any character except letters, numbers, and diagonal lines "\" can be used as delimiters, such as "#", "|", and "!". And so on.

Atom)

An atom is the basic unit of a regular expression. it should be a whole when analyzing regular expressions.
?? Atomic characters include all English letters, numbers, punctuation marks, and other symbols. The Atom also includes the following content.
?? Single character, number, such as a-z, A-Z, 0-9.
?? A pattern unit, such as ABC, can be understood as a large atom composed of multiple atoms.
?? Atomic table, such as [ABC].
?? The mode unit used again, for example, \ 1.
?? Common escape characters, such as \ d, \ D, \ w
?? Escape metacharacters, for example :\*,\.

Common escape characters

Atomic description
-----------------------------------------------------------------
\ D matches a number, which is equivalent to [0-9].
\ D matches any character except a number. it is equivalent to [^ 0-9].
\ W matches an English letter, number, or underline. it is equivalent to [0-9a-zA-Z _]
\ W matches any character except English letters, numbers, and underscores. it is equivalent to [^ 0-9a-zA-Z _]
\ S matches a blank character, which is equivalent to [\ f \ n \ r \ t \ v]
\ S matches any character except the white space. it is equivalent to [^ \ f \ n \ r \ t \ v]
\ F matching a page feed is equivalent to \ x0c or \ cL
\ N matches a line break, which is equivalent to \ x0a or \ cJ
\ R matching a carriage return is equivalent to \ x0d or \ cM
\ T matches a tab. it is equivalent to \ x09 \ or \ cl.
\ V matches a vertical tab, which is equivalent to \ x0b or \ ck
\ ONN matches an octal number
\ XNN matches a hexadecimal number
\ CC matches a control character

Metacharacters (Meta-character)

Metacharacters are special characters used to construct rule expressions. To include metacharacters in a regular expression, you must add "\" before it to escape it.
Metacharacters
-----------------------------------------------------------------
* Matches the previous atom 0 times, once, or multiple times
+ Match the previous atom once or multiple times
? Matches the previous atom zero or one time
| Match two or more options
^ Or \ A matches the first atom of A string
$ Or \ Z matches the atom at the end of a string
\ B matches the word boundary
\ B matches parts except word boundaries
[] Any atom in square brackets
[^] Match any character except the atom in square brackets
{M} indicates that the first atom exactly appears m times.
{M, n} indicates that the first atom appears at least m times and at least n times (n> m)
{M,} indicates that the first atom appears no less than m times.
() Indicates an atom.
. Match any character except line breaks

String boundary restrictions

In some cases, the matching range must be limited to obtain more accurate matching results. "^" And "$" respectively specify the start and end of the string.
?? For example, in the string "Tom and Jerry chased each other in the house until tom's uncelcome in ",
?? The metacharacters "^" or "\ A" are placed at the beginning of the string to ensure that the pattern match appears at the beginning of the string;
/^ Tom/
?? The metacharacters "$" or "\ Z" are placed at the end of the string to ensure that the tail end of the string appears in the pattern matching.
/In $/
?? If the boundary limit metacharacters are not added, more matching results will be obtained.
/^ Tom $/exact match/Tom/fuzzy match

Word boundary limit

When using the search function of various editing software, you can select "Search by word" to obtain more accurate results. Regular expressions also provide similar functions.
?? For example, in the string "This island is a beautiful land ",
?? The metacharacter "\ B" matches the word boundary;
/\ Bis \ B/matches the word "is" and does not match "This" or "island ".
// \ Bis/Matches "is" in the words "is" and "island", but does not match "This"
?? The metacharacter "\ B" matches parts except word boundaries.
/\ Bis \ B/does not match the left or right boundary of a word, but only matches the interior of a word. So there is no result in this example.
// \ Bis/match "is" in the word "This"

Duplicate match

There are some metacharacters used to repeatedly match certain atoms in the regular expression: "?" , "*", "+ ". The main difference between them is that the number of repeated matches varies.
?? Metacharacters "?" : Indicates 0 times or 1 time matching the atom immediately before it.
Example:/colou? R/match "color" or "color ".
?? Metacharacter "*": indicates zero, one, or multiple matches to the atom immediately before it.
For example:/zo */can match z and zoo
?? Metacharacters "+": indicates an atom that matches one or more times before it.
For example,/go + gle/Matches "gogle", "google", or "gooogle" among other strings containing multiple o.

Any one character

The metacharacter "." matches any character except the linefeed.
?? Equivalent to [^ \ n] (Unix system) or [^ \ r \ n] (windows system ).
?? For example,/pr. y/can match strings such as "prey", "pray", or "pr % y.
?? Generally, you can use the ". *" combination to match any character except the line break. In some books, it is also called "full match" or "single match ".
?? For example:
?? /^ A. * z $/indicates a string that matches the start of the letter "a" and ends with the letter "z" without line breaks.
?? /. +/Similar matching functions can be completed. The difference is that it matches at least one character.
?? /^ A. + z $/matching "a % z" does not match the string "az"

Atomic table-Square brackets

The atomic table "[]" contains a group of atoms, which are equal to each other and match only one of them. If you want to match a "a" or "e", use [AE].
?? For example, Pr [AE] y matches "Pray" or "Prey ".
?? The atomic table "[^]", or the excluded atomic table, matches any character except the atom in the table.
?? For example,/p [^ u]/Matches "pa" in "part", but cannot match "pu" in "computer" because "u" is excluded in matching.
?? The atomic table "[-]" is used to connect a group of atoms arranged in ASCII order to simplify writing.
?? For example,/x [0123456789]/can be written as x [0-9] to match a string consisting of an "x" letter and a number.
?? For example:
?? /[A-zA-Z]/match all uppercase and lowercase letters
?? /^ [A-z] [0-9] $/match such as "z2", "t6", and "g7"
?? /0 [xX] [0-9a-fA-F]/matches a simple hexadecimal number, such as "0x9 ".
?? /[^ 0-9a-zA-Z _]/matches any character except English letters, numbers, and underscores. it is equivalent to \ W.
?? /0? [XX] [0-9a-fA-F] +/matches hexadecimal numbers, such as "0x9B3C" or "X800.
?? /<[A-Za-z] [A-Za-z0-9] *>/can match"

"," "Or""And other HTML tags, and the case sensitivity is not strictly controlled.

Mode Selector

The metacharacter "|" is also called the mode selector. Match two or more options in the regular expression.
?? For example:
?? In the string "There are supported apples and pears.",/apple | pear/Matches "apple" at the first run and pear at the second run ". You can also add more options, such as/apple | pear | banana | lemon/

Mode unit

The metacharacter "()" is used to change the regular expression to an atom (or a pattern unit. Like brackets in mathematical expressions, "()" can be used as a unit separately.
?? For example:
?? /(Dog) +/Matches "Dog", "DogDog", and "DogDogDog", because the atom before "+" is the metacharacter "() the enclosed string "Dog ".
?? /You (very) + old/Matches "You very old" and "You very veryold"
?? /Hello (world | earth)/Matches "Hello world" and "Hello earth"
?? Expressions in a pattern unit are preferentially matched or computed.

Mode unit for reuse

The system automatically stores the matches in the mode Unit "()" in sequence and can reference them in the form of "\ 1", "\ 2", and "\ 3" as needed. When a regular expression contains the same pattern unit, this method is very easy to manage. Note that "\ 1" and "\ 2" must be written for use"
For example:
?? /^ \ D {2} ([\ W]) \ d {2} \ 1 \ d {4} $/matches strings such as "12-31-2006", "09/27/1996", and "86 01 4321. However, the above regular expression does not match the "12/34-5678" format. This is because the result "/" of the mode "[\ W]" has been stored. When the next position "\ 1" is referenced, the matching mode is also the character "/".
?? When you do not need to store matching results, use the non-storage mode Unit "(? :)"
?? For example /(? : A | B | c) (D | E | F) \ 1g/will match "aEEg ". In some regular expressions, it is necessary to use non-storage mode units. Otherwise, you need to change the subsequent reference sequence. The preceding example can also be written as/(a | B | c) (C | E | F) \ 2g /.


The above introduces regular expressions (39), including some content, and hope to be helpful to friends who are interested in PHP tutorials.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.