PHP Regular Expression Full manual

Source: Internet
Author: User
Tags alphabetic character php regular expression printable characters

PHP Regular Expression full manual preface the regular expression is cumbersome, but powerful, learned after the application will let you in addition to improve efficiency, will give you an absolute sense of accomplishment. It is not a problem to master regular expressions, as long as you read them carefully, add some references when applying them. Index1._ Intro2._ The history of regular Expressions3._ Regular Expression Definitions3.1_ Ordinary characters3.2_ non-printable characters3.3_ Special Characters3.4_ Qualifier3.5_ Locator3.6_ Selection3.7_ back to reference4._ operator precedence for various operators5._ All symbols explained6._ Some examples7._ Regular expression matching rules7.1_ basic pattern matching7.2_ character clusters7.3_ to confirm recurring occurrences1.intro at present, regular expressions have been widely used in many software, including*nix (Linux, UNIX, etc.), HP and other operating systems, PHP,C#, the development environment such as Java, as well as many application software, can see the shadow of the regular expression. The use of regular expressions can be achieved through a simple approach to powerful functions.   In order to be simple and effective without losing strong, resulting in regular expression code difficult, learning is not very easy, so need to pay some effort to do, after the introduction of reference to certain references, use up or relatively simple and effective. Example:^[email protected]+\\. +$ This kind of code used to scare me off a lot. Maybe a lot of people are scared to run away by this kind of code.   Continuing to read this article will allow you to freely apply such code. Note: The 7th part here looks somewhat repetitive, with the intention of re-describing the sections in the previous table to make the content easier to understand. 2.The "ancestor" of the regular expression's historical regular expression can be traced back to the early study of how the human nervous system works.   Warren McCulloch and Walter Pitts the two neuroscientists have developed a mathematical approach to describe these neural networks. 1956,A mathematician named Stephen Kleene, on the basis of the early work of McCulloch and Pitts, published a paper titled "Representation of Neural network events", introducing the concept of regular expressions.   The regular expression is the expression that describes what he calls "the algebra of the regular set", so the term "regular expression" is used. Later, it was discovered that this work could be applied to some early studies of the computational search algorithm using Ken Thompson, the main inventor of Unix.   The First Utility application of a regular expression is the QED editor in Unix. As they say, the rest is a well-known history. Since then, regular expressions have been an important part of text-based editors and search tools. 3.regular expression definition regular expression (regular expression) describes a pattern of string matching that can be used to check whether a string contains a seed string, replaces a matched substring, or extracts a substring that matches a certain condition from a string. Column directory,dirThe *.txt in *.txt or LS *.txt is not a regular expression, as there is * with the regular type *The meaning of this is different. Regular expressions are text patterns that consist of ordinary characters, such as characters A through z, and special characters (called metacharacters).   A regular expression, as a template, matches a character pattern to the string you are searching for. 3.1ordinary characters consist of all printed and non-printable characters that are not explicitly specified as metacharacters.   This includes all uppercase and lowercase alphabetic characters, all numbers, all punctuation marks, and some symbols. 3.2nonprinting character characters mean that \cx matches the control character indicated by X. For example, \cm matches a Control-m or carriage return character. The value of x must be one of a-Z or a-Z. Otherwise, c is considered to be a literal ' C 'characters. \f matches a page break. Equivalent to \x0c and \CL. \ n matches a line break. Equivalent to \x0a and \CJ. \ r matches a carriage return character. Equivalent to \x0d and \cm. \s matches any whitespace character, including spaces, tabs, page breaks, and so on. equivalent to [\f\n\r\t\v]. \s matches any non-whitespace character. equivalent to [^\f\n\r\t\v]. \ t matches a tab character. Equivalent to \x09 and \ci. \v matches a vertical tab.    Equivalent to \x0b and \ck. 3.3Special characters , the so-called special characters, are some characters with special meanings, as stated above"*.txt" in the *, simply means that the meaning of any string. If you are looking for a file with * in the file name, you need to escape the *, which is preceded by a \. LS \*.txt. The regular expression has the following special characters. The special character description matches the end position of the input string. If you set the Multiline property of the RegExp object, it also matches' \ n ' or ' \ R '. To match the $ character itself, use \$. () to mark the start and end positions of a sub-expression. Sub-expressions can be obtained for later use. To match these characters, use \ (and \). * matches the preceding subexpression 0 or more times. To match the * character, use \*. + matches the preceding subexpression one or more times. to match the + character, use the \+. . Matches any single character except for the newline character \ n. to match., please use \. [Marks the beginning of a bracket expression. to match [, please use \[. ? Matches the preceding subexpression 0 or one time, or indicates a non-greedy qualifier. to match? characters, please use \?. \ marks the next character as either a special character, or a literal character, or a backward reference, or octal escape character. For example,' n ' matches the character ' n '. ' \ n ' matches line breaks. The sequence ' \ \ ' matches ' \ ', while ' \ (' then Match ' (". ^ matches the starting position of the input string, unless used in a square bracket expression, at which point it indicates that the character set is not accepted. To match the ^ character itself, use \^. {The beginning of the tag qualifier expression.} To match {, use \{. | Indicates a choice between the two items.    to match |, please use \|. The method of constructing a regular expression is the same as the method for creating a mathematical expression. That is, using a variety of meta-characters and operators to combine small expressions together to create larger expressions.    A component of a regular expression can be a single character, a character set, a range of characters, a selection between characters, or any combination of all of these components. The 3.4 qualifier qualifier is used to specify how many times a given component of a regular expression must appear to satisfy a match.   There are 6 types of * or + or? or {n} or {n,} or {n,m}.   The *, +, and? Qualifiers are greedy because they match as many words as possible, but only after they are added with one? You can implement a non-greedy or minimal match. The qualifier for a regular expression is: A character description * matches the preceding subexpression 0 or more times. For example, zo* can match"Z" and "Zoo". * Equivalent to {0,}. + matches the preceding subexpression one or more times. For example, ' zo+ ' can match"Zo" and "Zoo", but cannot match "Z". + equivalent to {1,}.? Matches the preceding subexpression 0 or one time. For example," Do(es)? " Can match " Do"or" does "in the" Do".? is equivalent to {0,1}. {n} n is a non-negative integer. Matches the determined n times. For example, ' o{2} ' does not match' O ' in "Bob", but matches "food"in the two O. {N,} n is a non-negative integer. Match at least n times. For example, ' o{2,} ' does not match' O ' in "Bob", but can match "Foooood"all of the O. ' O{1,} ' is equivalent to ' o+ '. ' O{0,} ' is equivalent to ' o* '. {n,m} m and n are non-negative integers, where n <= m. Matches at least n times and matches up to M times. For example,"o{1,3}" will match "Fooooood"the first three O. ' o{0,1} ' is equivalent to ' O? '.   Note that there can be no spaces between a comma and two numbers. 3.5 Locators are used to describe the boundaries of a string or word, ^ and$ refers to the start and end of a string, respectively, \b describes the front or back boundaries of a word, and \b represents a non-word boundary.   You cannot use qualifiers on locators. 3.6 Choose to enclose all selections in parentheses, separating the adjacent selections by |.   But with parentheses there is a side effect that the associated match is cached and available at this time?: Put the first option to eliminate this side effect. Where?: one of the non-capturing elements, and two non-capturing elements are? = and?!, these two also have more meanings, the former is forward pre-check, in any beginning to match the position of the regular expression pattern within the parentheses to match the search string, the latter is a negative pre-check,   Matches the search string at any start where the regular expression pattern does not match. 3.7 Back reference adding parentheses around a regular expression pattern or part of a pattern causes the related match to be stored in a temporary buffer, and each captured sub-match is stored according to what is encountered from left to right in the regular expression pattern. The buffer number for the storage sub-match starts at 1 and continues numbering up to 99 sub-expressions.   Each buffer can be accessed using ' \ n ', where n is a single or two-bit decimal number that identifies a particular buffer. You can use the non-capturing metacharacters '?: ', '? = ', or '?! ' to ignore the save of the related match. 4. Operators of various operators with the same priority of precedence of the operation from left to right, the operation of different priorities first high and low. The precedence of the various operators is from high to low as follows: operator description \ Escape character (), (?:), (? =), [] parenthesis and square brackets *, +,?, {n}, {n,}, {n,m} qualifier ^, $, \anymetacharacter position and order | "or" Action 5. All symbols explain the character description \ marks the next character as a special character, or a literal character, or a backward reference, or an octal escape character. For example, ' n ' matches the character"N". ' \ n ' matches a line break. The sequence ' \ \ ' matches ' \ ' and ' matches ' (". Matches the starting position of the input string. If you set the Multiline property of the RegExp object, it also matches the position after ′\n′ or ′\r′.$ matches the end position of the input string。 If you set the Multiline property of the RegExp object,$ also matchesThe position before ′\n′ or ′\r′. ∗ matches the preceding subexpression 0 or more times. For example, zo∗ can match "z" and "Zoo". The ∗ is equivalent to 0. + matches the preceding subexpression one or more times. For example, ′zo+′ can match "Zo" and "Zoo", but not "Z". + equivalent to 1,。? match the preceding subexpression 0 or one time. For example, " Do(es)? " Can match " Do"or" does "in the" Do".?" is equivalent to 0, 1. NN is a non-negative integer. Matches the determined n times. For example, ′o2′ cannot match ′o′ in "Bob," but can match two o in "food". N,n is a non-negative integer. Match at least n times. For example, ′o2,′ cannot match ′o′ in "Bob", but can match all o in "Foooood". ′o1,′ is equivalent to ′o+′. ′o0,′ is equivalent to ′o∗′. Both N,MM and n are non-negative integers, where n<=m. Matches at least n times and matches up to M times. For example, "o1,3" will match the first three o in "Fooooood". ′o0,1′ is equivalent to ′o?′. Note that there can be no spaces between commas and two numbers. When the character is immediately behind any other restriction (∗,+,?, n,n,,n,m), the matching pattern is non-greedy. The non-greedy pattern matches the searched string as little as possible, while the default greedy pattern matches as many of the searched strings as possible. For example, for the string "Oooo", ′o+?′ will match a single "O", and ′o+′ will match all ′o′: match except "\ n"any single character outside of the To match any character including ′\n′, use a pattern like ′[.\n]′. Pattern matches the pattern and gets the match. The obtained matches can be obtained from the resulting matches collection, the Submatches collection is used in VBScript, and the $0...$9 property is used in JScript. To match the parentheses character, use ′\ (or. (?:p Attern) matches the pattern but does not get a matching result, which means that this is a non-fetch match and is not stored for later use. This is usedOrcharacter (|) to combine parts of a pattern is useful. For example, ' Industr (?: y|ies) is a more abbreviated expression than ' industry|industries '. (? =pattern) forward, matching the lookup string at the beginning of any string that matches the pattern. This is a non-fetch match, which means that the match does not need to be acquired for later use. For example, ' Windows (? =95|98| nt|2000) ' Can matchWindows in Windows 2000, but does not match windows in Windows 3.1. Pre-checking does not consume characters, that is, after a match occurs, the next matching search starts immediately after the last match, rather than starting with the character that contains the pre-check. (?! pattern), which matches the lookup string at the beginning of any string that does not match the pattern. This is a non-fetch match, which means that the match does not need to be acquired for later use. For example ' Windows (?! 95|98| nt|2000) ' Can matchWindows in Windows 3.1, but does not match windows in Windows 2000. Pre-checking does not consume characters, that is, after a match has occurred, the next matching search starts immediately after the last match, rather than starting x|y match X or y after the character that contains the pre-check. For example, ' Z|food ' can match"Z" or "food". ' (z|f) Ood ' matches "Zood" or "food". [XYZ] Character set. Matches any one of the characters contained. For example, ' [ABC] ' can match"Plain"in the ' a '. [^XYZ] negative character set. Matches any character that is not contained. For example, ' [^ABC] ' can match"Plain"in the ' P '. A [A-z] character range. Matches any character within the specified range. For example, ' [A-z] ' can match any lowercase alphabetic character in the ' a ' to ' Z ' range. [^a-z] negative character range. Matches any character that is not in the specified range. For example, ' [^a-z] ' can match any character that is not within the range of ' a ' to ' Z '. \b Matches a word boundary, which is the position between a word and a space. For example, ' er\b ' can match' Er ' in "never", but cannot match "verb"in the ' er '. \b Matches a non-word boundary. ' er\b ' can match' er ' in "verb", but cannot match "never"in the ' er '. \CX matches the control character indicated by X. For example, \cm matches a control-m or carriage return. The value of x must be one of a-Z or a-Z. Otherwise, c is treated as a literal ' C ' character. \d matches a numeric character. equivalent to [0-9]. \d matches a non-numeric character. equivalent to [^0-9]. \f matches a page break. Equivalent to \x0c and \CL. \ n matches a line break. Equivalent to \x0a and \CJ. \ r matches a carriage return character. Equivalent to \x0d and \cm. \s matches any whitespace character, including spaces, tabs, page breaks, and so on. equivalent to [\f\n\r\t\v]. \s matches any non-whitespace character. equivalent to [^ \f\n\r\t\v]. \ t matches a tab character. Equivalent to \x09 and \ci. \v matches a vertical tab. Equivalent to \x0b and \ck. \w matches any word character that includes an underscore. Equivalent to ' [a-za-z0-9_] '. \w matches any non-word character. Equivalent to ' [^a-za-z0-9_] '. \XN matches N, where n is the hexadecimal escape value. The hexadecimal escape value must be two digits long for a determination. For example, ' \x41 ' matches"A". ' \x041 ' is equivalent to ' \x04 ' & ' 1 '"Once Upon A Time"Match, and" there once is a man from NewYork "does not match. Just as the ^ symbol indicates the beginning,The $ symbol is used to match strings that end in a given pattern. bucket$ this pattern with"Who kept all of the cash in a bucket" match, and "buckets" does not match. Characters ^ and$ when used simultaneouslythat represents an exact match (the string is the same as the pattern). Example: ^bucket$ matches only strings"Bucket". If a pattern does not include ^ and $, then it matches any string that contains the pattern.   For example: pattern once with string there once is a man from NewYork who kept all of his cash in a bucket.  is a match. The letters in the pattern (O-N-C-E) are literal characters, that is, they represent the letter itself, and the numbers are the same. Some other slightly more complex characters, such as punctuation and white characters (spaces, tabs, etc.), are used to escape sequences. All escape sequences begin with a backslash (\). The escape sequence for a tab is: \ t. So if we're going to check if a string starts with a tab, you can use this pattern: ^\t similar to \ n for "new line", \ r for Enter.   Other special symbols can be used in front with a backslash, such as the backslash itself with \ \, period. Use \. To indicate, and so on. 7.2 character clusters in programs in the Internet, regular expressions are often used to validate the user's input.   When the user submits a form, to determine whether the input phone number, address, email address, credit card number, etc. is valid, with ordinary literal-based characters is not enough. So to use a more liberal way of describing the pattern we want, it's a character cluster. To create a character cluster that represents all vowel characters, place all the vowels in a square bracket: [Aaeeiioouu] This pattern matches any vowel character, but only one character. A hyphen can be used to denote a range of characters, such as: [A-z]//Match all lowercase letters [a-z]//Match all capitals [a-za-z]//Match all the letters [0-9]//Match all the numbers [0-9\.\-]//Match all the numbers, period and minus sign [\f\r\t\n]//Match all white characters the same, these also represent only one character, which is a very important one. If you want to match a string consisting of a lowercase letter and a single digit, such as"Z2", "T6" or "G7", but not "ab2", "r2d3", or "B52", use this mode: ^[a-z][0-9]$ Although [A-z] represents a range of 26 letters, here it can only match a string with the first character being a lowercase letter. The previous mention of ^ represents the beginning of a string, but it has another meaning. When used in a set of square brackets ^ is, it means "non" or "exclude" meaning, often used to remove a character. Also with the previous example, we ask that the first character cannot be a number: ^[^0-9][0-9]$ this pattern with"&5", "G7" and "2" are matched, but with "12", "66"is not matched. Here are a few examples of excluding specific characters: [^a-z]//Except lowercase letters all characters [^\\\/\^]//except for (\) (/) (^) all characters [^\ "\"]//except double quotation marks (") and single quotation marks (') except for all characters special characters "." (point, period) is used in regular expressions to denote all characters except the "New line". So the pattern "^.5$" matches any two-character string that ends with the number 5 and begins with other non-"new line" characters. Mode "."   You can match any string, except for an empty string, and to include only a "new line" of strings. The regular expressions for PHP have some built-in universal character clusters, which are listed as follows: The meaning of the character cluster [[: Alpha:]] any number [[: Igit:]] any digit [[£ alnum:]] Any letters and numbers [[: Space:]] any white-letter [[: Up]] Per:]] any uppercase letters [[: Lower:]] any lowercase letter [[: Xdigit:]] Any punctuation mark [[:p UNCT:]] Any 16-digit number, equivalent to [0-9a-fa-f] 7.3 ok repetition appears so far as you already know How to match a letter or number, but more likely to match a word or a set of numbers. A word consists of several letters, and a group of numbers has several singular parts.   The curly braces ({}) following the character or character cluster are used to determine the number of occurrences of the preceding content. Character cluster meaning ^[a-za-z_] all letters and underscores [[: Alpha:]]3 all 3-letter words ^a a A4 aaaa ^a{2,4}aa,aaa or aaaa a1,3 A,aa or AAA ^a{2,}$ contain more than two A string ^a{2,} such as: Aardvark and Aaab, but Apple does not a{2,} such as: Baad and AAA, but Nantucket not \t{2} two tabs. {2} All two characters these examples describe three different uses of curly braces. A number, {x}, means "the preceding character or character cluster appears only x times"; A number plus a comma, {x,} means "x or more occurrences of the preceding content", and two comma-delimited numbers, {x, y} means "the preceding content appears at least x times, but not more than Y". We can extend the pattern to more words or numbers: ^[a-za-z0-9_]{1,}//all strings that contain more than one letter, number, or underscore [0−9]1,//All positive numbers ^\-{0,1}[0-9]{1,}//all integers \-0,1[0−9]0, \.0,1[0−9]0,//The last example of all decimals is not very well understood, is it? So look at it: with all with an optional minus sign (\-{0,1}) Start (^), followed by 0 or more digits ([0-9]{0,}), and an optional decimal point (\.{ 0,1}) followed by 0 or more numbers ([0-9]{0,}), and nothing else ($).   Below you will know the simpler way to use it. Special characters "?" is equal to {0,1}, and they all represent: "0 or 1 preceding content" or "previous content is optional". So just the example can be simplified as: ^\-? [0-9] {0,}\.? [0-9] {0,}$ special characters "*" are equal to {0}, and they all represent "0 or more of the preceding content." Finally, the character "+" is equal to {1,}, which means "1 or more preceding contents", so the above 4 examples can be written as: ^[a-za-z0-9_]+//all strings that contain more than one letter, number, or underscore [0−9]+//All positive ^\-? [0-9]+//all the integer \-? [0−9]∗\.? [0−9]∗//all decimals of course this does not technically reduce the complexity of formal expressions, but it makes them easier to read. For more information, refer to: http://www.jb51.net/article/26215.htm

 

Related Article

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.