Research on PHP regular expressions

Source: Internet
Author: User
Tags alphanumeric characters expression engine
The study of PHP regular expressions is a very powerful tool. we may use it anywhere...

Regular expressions are a very powerful tool. we may use them anywhere...
I have worked hard on regular expressions, but I still forget it after a long time...
Let's take a look at it again today. I saw a good article, so I just transferred it to my favorites.
If you are confused about regular expressions, this article will certainly help you. ^. ^
Link: http://www.cnblogs.com/dragon/archive/2006/05/08/394078.html

Preface:
I became interested in regular expressions half a year ago. I searched for a lot of information on the Internet, read a lot of tutorials, and finally found that his tutorial was very well written when I used RegexBuddy, a regular expression tool, it can be said that it is the best regular expression tutorial I have ever seen. So I always wanted to translate it. This wish will not be realized until this May Day holiday, and this article will be available. For the name of this article, it seems that it is too common to use "in simple terms. However, after reading the original article, I feel that only by using "in-depth and simple" can I express the experience this tutorial has given me, so I cannot avoid it.
This article is the translation of the tutorial written by Jan Goyvaerts for RegexBuddy. the copyright belongs to the original author. However, to respect the work of the original author and the translator, please indicate the source! Thank you!

 

1.What is a regular expression?

Basically, a regular expression is a pattern used to describe a certain number of texts. Regex represents Regular Express. This article uses < > To represent a specific regular expression.

A piece of text is the most basic mode. it simply matches the same text.

2.Different regular expression engines

The regular expression engine is a software that can process regular expressions. Generally, the engine is part of a larger application. In the software world, different regular expressions are not compatible with each other. This tutorial will focus on Perl 5 engines, which are the most widely used engines. At the same time, we will also mention some differences with other engines. Many modern engines are similar, but not identical. For example, the. NET regular expression library and JDK regular expression package.

3.Text symbols

The most basic regular expression is composed of a single text symbol. For example, <>, it matches the first occurrence of the character "a" in the string ". For example, for the string "Jack is a boy ". "A" after "J" will be matched. The second "a" won't be matched.

The regular expression can also match the second "a", which must be the place where you tell the regular expression engine to start searching from the first match. In the text editor, you can use "find next ". In programming languages, there is a function that enables you to continue searching backward from the previous matched position.

Similarly, < > It matches "cat" in "About cats and dogs ". This tells the regular expression engine to find a < >, Followed by one <>, followed by another < >.

Note that the regular expression engine is case sensitive by default. Unless you tell the engine to ignore case sensitivity, otherwise < > "Cat" is not matched ".

  • Special characters

12 characters are reserved for special purposes. They are:

[] \ ^ $. |? * + ()

These special characters are also called metacharacters.

If you want to use these characters as text characters in a regular expression, you need to use the backslash "\" to encode them (escape ). For example, if you want to match "1 + 1 = 2", the correct expression is <1 \ + 1 = 2>.

<1 + 1 = 2> is also a valid regular expression. But it does not match "1 + 1 = 2", but will match "123 = 2" in "111 + 234 = 111 ". Because "+" represents a special meaning here (repeated once to multiple times ).

In programming languages, note that some special characters are first processed by the compiler and then passed to the regular expression engine. Therefore, the regular expression <1 \ + 2 = 2> must be written as "1 \ + 1 = 2" in C ++ ". To match "C: \ temp", you must use a regular expression < >. In C ++, the regular expression is changed to "C: \ temp ".

  • Non-printable characters

Special character sequences can be used to indicate certain non-printable characters:

<\ T> Tab (0 × 09)

<\ R> represents the carriage return (0x0D)

<\ N> represents a line break (0x0A)

Note that in Windows, "\ r \ n" is used to end a line, while "\ n" is used for Unix ".

4.Internal working mechanism of the regular expression engine

Knowing how the regular expression engine works helps you quickly understand why a regular expression does not work as expected.

There are two types of engines: the text-directed engine and the regex-directed engine. Jeffrey Friedl calls them the DFA and NFA engines. This article talks about the regular expression-oriented engine. This is because some very useful features, such as lazy quantifiers and backreferences, can only be implemented in the regular expression-oriented engine. So it is not surprising that this engine is currently the most popular.

You can easily tell whether the engine is text-oriented or regular-expression-oriented. If reverse references or "inert" quantifiers are implemented, you are sure that the engine you are using is regular-oriented. You can test the regular expression as follows: < > Apply the string "regex not ". If the matching result is regex, the engine is regular-oriented. If the result is regex not, it is text-oriented. Because the regular expression-oriented engine is a "monkey" engine, it will be eager to make an expression and report the first matching it finds.

  • The regular expression-oriented engine always returns the leftmost match.

This is a very important point you need to understand: even if you may find a "better" match in the future, the regular expression-oriented engine always returns the leftmost match.

When < > Apply it to "He captured a catfish for his cat", and the engine first compares < > And "H", the result failed. So the engine is compared again < > And "e" also fail. Until the fourth character, < > Matches "c ". <> The fifth character is matched. To the sixth character < > Failed to match "p. The engine re-checks the matching from the fifth character. It is up to 15th characters, < > After matching "cat" in "catfish", the regular expression engine eagerly returns the first matching result without continuing to look for other better matches.

5.Character set

Character set is a character set that is enclosed by a pair of square brackets. Using character sets, you can tell the regular expression engine to match only one of multiple characters. If you want to match a "a" or an "e", use <[AE]>. You can use < > Match gray or gray. This is especially useful when you are not sure whether the character you want to search for is in American or English. On the contrary, < > It will not match graay or graey. The character sequence in the character set is irrelevant and the results are the same.

You can use the hyphen "-" to define a character range as a character set. <[0-9]> match a single number between 0 and 9. You can use more than one range. <[0-9a-fA-F]> matches a single hexadecimal number and is case insensitive. You can also combine the range definition with a single character definition. <[0-9a-fxA-FX]> match a hexadecimal number or letter X. Again, the sequence of characters and range definitions does not affect the result.

  • Application of character set

Find a word that may have misspelled characters, such as < > Or < >.

Find the identifier of the program language, <>. (* Indicates repeated 0 or multiple times)

Find the hexadecimal number of the C style <0 [xX] [A-Fa-f0-9] +>. (+ Indicates repeat once or multiple times)

  • Inverse character set

The character set is reversed when the left square brackets ([) are followed by an angle bracket (^. The result is that the character set matches any character that is not in square brackets. Unlike ".", the anti-character set can match the carriage return line break.

It is important to remember that a character must be matched to the anti-character set. < > This does not mean that q is matched and no u is followed. It means: match a q, followed by a character not u. Therefore, it will not match q in "Iraq", but will match q in "Iraq is a country" and a space character. In fact, a space character is a part of the match because it is a "not a u character ".

If you only want to match a q, the condition is that q is followed by a character that is not u. we can solve this problem by looking forward as described later.

  • Metacharacters in the character set

Note that only four characters in the character set have special meanings. They are: "] \ ^ -". "]" Indicates the end of the character set definition; "\" indicates the escape, "^" indicates the inverse, and "-" indicates the range definition. Other common metacharacters are normal characters in the character set definition and do not need to be escaped. For example, to search for asterisks * or plus signs +, you can use <[+ *]>. Of course, if you escape common metacharacters, your regular expression will work well, but this will reduce readability.

In character set definition, to use the backslash "\" as a character rather than a special character, you need to use another backslash to escape it. <[\ X]> a backslash and an X are matched. "] ^-" Can be escaped by backslash, or placed in a position that cannot be used to their special meaning. We recommend the latter because it increases readability. For example, if the character "^" is placed after the left bracket "[", it uses the text character meaning rather than the inverse meaning. For example, <[x ^]> matches an x or ^. <[] X]> A "]" or "x" is matched ". <[-X]> or <[x-]> match a hyphen (-) or hyphen (x ".

  • Character set abbreviations

Some character sets are very common, so there are some shorthand methods.

<\ D> representative <[0-9]>;

<\ W> represents a word character. This varies with the implementation of regular expressions. The word character sets implemented by most regular expressions include <>.

<\ S> indicates "white characters ". This is also related to different implementations. In most implementations, space characters, Tab characters, and carriage return linefeeds <\ r \ n> are included.

Character set abbreviations can be used within or out of square brackets. <\ S \ d> match a white character followed by a number. <[\ S \ d]> match a single white character or number. <[\ Da-fA-F]> a hexadecimal number is matched.

Abbreviation of the inverse character set

<[\ S] >>=< <[^ \ s]>

<[\ W] >>=< <[^ \ w]>

<[\ D] >=< <[^ \ d]>

  • Duplicate character set

If you use "? * + "Operator to repeat a character set. you will repeat the entire character set. It is not only the character it matches. The regular expression <[0-9] +> matches 837 and 222.

If you only want to repeat the matched character, you can use backward reference for the purpose. We will talk about backward reference later.

6.Use? *Or +Duplicate

? : Tells the engine to match the leading character 0 times or once. In fact, it indicates that the leading character is optional.

+: Tell the engine to match the leading character once or multiple times

*: Tells the engine to match the leading character 0 or multiple times

<[A-Za-z] [A-Za-z0-9] *> matches HTML tags without attributes, and "<" and ">" are text symbols. The first character set matches a letter, and the second character set matches a letter or number.

We seem to be able to use <[A-Za-z0-9] +>. But it will match <1>. However, this regular expression is valid when you know that the string you want to search for does not contain similar invalid tags.

  • Duplicate restriction

Many modern regular expression implementations allow you to define how many times a character is repeated. Lexical: {min, max }. Both min and max are non-negative integers. If a comma exists and max is ignored, max is not restricted. If both comma and max are ignored, repeat the time in minutes.

Therefore, {0,} is the same as *, and {1,} is the same as +.

You can use <\ B [1-9] [0-9] {3} \ B> to match 1000 ~ A number between 9999 ("\ B" indicates the word boundary ). <\ B [1-9] [0-9] {2, 4} \ B> match a value between 100 and ~ A number between 99999.

  • Pay attention to greed

Suppose you want to use a regular expression to match an HTML tag. You know that the input will be a valid HTML file, so regular expressions do not need to exclude invalid tags. Therefore, if the content is between two angle brackets, it should be an HTML tag.

Many new users of the regular expression will first think of using the regular expression <. +>, they will be surprised to find that for the test string, "This isFirstTest ", you may expect to return, And then return.

But it does not. The regular expression will matchFirst". Obviously, this is not the result we want. The reason is that "+" is greedy. That is to say, "+" will cause the regular expression engine to try to repeat leading characters as much as possible. The engine performs backtracking only when this type of repetition causes the entire regular expression to fail to match. That is to say, it will discard the last "repeat" and then process the remaining part of the regular expression.

Like "+", "? * "Repetition is greedy.

  • Go deep into the regular expression engine

Let's take a look at how the regular expression engine matches the previous example. The first mark is "<", which is a text symbol. The second symbol is ".", matches the character "E", and "+" can always match other characters until the end of a line. Then the linefeed fails to match ("." does not match the linefeed ). The engine starts to match the next regular expression symbol. That is, try to match "> ". So far, "<. +" has matched"FirstTest ". The engine tries to match ">" with the linefeed and the result fails. The engine traces back. The result is that "<. +" matches"First". Therefore, the engine matches ">" with "t. Obviously, it will still fail. This process continues until "<. +" matches"First"Matches">. So the engine finds a matching"First". Remember, the regular expression-oriented engine is "eager", so it will rush to report the first match it finds. Rather than continue tracing, even if there may be better matching, such as"". Therefore, we can see that due to the greedy nature of "+", the regular expression engine returns a leftmost longest match.

  • Replace greed with laziness

One possible solution for correcting the above problems is to replace greed with "+" inertia. You can follow "+" with a question mark "?" To achieve this. "*", "{}" And "?" This scheme can also be used for repeated representation. Therefore, in the preceding example, we can use "<. +?> ". Let's take a look at the processing process of the regular expression engine.

Again, the regular expression Mark "<" matches the first "<" of the string ". The next regular Mark is ".". This is a lazy "+" to repeat the previous character. This tells the regular expression engine to repeat the previous character as few as possible. Therefore, the engine matches "." and the character "E", and then matches "M" with ">". The result fails. The engine will perform backtracking. Unlike the previous example, because it is a inertia repetition, the engine expands the inertia repetition rather than reduces, so "<. +" is now extended to" ". A successful match is obtained this time. The engine reports" "Is a successful match. The entire process is roughly the same.

  • An alternative to inert scaling

We also have a better alternative. You can use a greedy repeat with an anti-character set: "<[^>] +> ". This is a better solution. when the inertia repeat is used, the engine will backtrack each character before finding a successful match. However, you do not need to perform backtracking when using the anti-character set.

The last thing to remember is that this tutorial only talks about the regular expression-oriented engine. The text-oriented engine does not trace back. At the same time, they do not support inert and repetitive operations.

7.Use "."Matches almost any character

In regular expressions, "." is one of the most commonly used symbols. Unfortunately, it is also one of the most vulnerable symbols to misuse.

"." Matches a single character without worrying about the character to be matched. The only exception is the newline character. The engine mentioned in this tutorial does not match the new line character by default. Therefore, by default, "." is equivalent to the abbreviation of the character set [^ \ n \ r] (Window) or [^ \ n] (Unix.

This exception is due to historical reasons. Because the regular expression-based tools were used in the early days. They all read a file in one row and apply the regular expression to each row. In these tools, strings do not contain newline characters. Therefore, "." never matches New Line characters.

Modern tools and languages can apply regular expressions to large strings or even entire files. All regular expression implementations discussed in this tutorial provide an option to make "." match all characters, including New Line characters. In RegexBuddy, EditPad Pro, PowerGREP, and other tools, you can simply select "point matching newline ". In Perl, the pattern that "." can match a newline is called "single line pattern ". Unfortunately, this is a confusing term. Because there is also the so-called "multiline mode ". The multi-row mode only affects anchor at the beginning and end of the line, while the single-row mode only affects ".".

Other languages and regular expression libraries also use Perl terminology. When using a regular expression class in. NET Framework, you can use a statement similar to the following to activate the single-row mode: Regex. Match ("string", "regex", RegexOptions. SingleLine)

  • Conservative use of the "."

Point numbers can be said to be the most powerful metacharacters. It allows you to be lazy: with a dot, you can match almost all characters. But the problem is that it often matches characters that do not match.

I will give a simple example. Let's see how to match a date in mm/dd/yy format, but we want to allow users to select separators. One solution that will soon come up with is <\ d. \ d. \ d>. It seems that it matches the date "02/12/03 ". The problem is that 02512703 is also considered a valid date.

<\ D [-/.] \ d [-/.] \ d> it looks like a better solution. Remember that the point number is not a metacharacter in a character set. This solution is far from perfect, and it will match "99/99/99 ". <[0-1] \ d [-/.] [0-3] \ d [-/.] \ d> goes further. Even though it matches "19/39/99 ". The degree to which you want your regular expression to be perfect depends on what you want to do. If you want to verify user input, try to be as perfect as possible. If you only want to analyze a known source and we know that there is no error data, it is enough to use a better regular expression to match the characters you want to search.

 

8.String start and end anchor

The anchor is different from the regular expression symbol. it does not match any character. Instead, they match the positions before or after the characters. "^" Matches the position before the first character of a string. <^ A> match a in the string "abc. <^ B> it does not match any character in "abc.

Similarly, $ matches the position behind the last character in the string. So < > Match c in "abc.

  • Anchored applications

When verifying user input in programming languages, it is very important to use the anchor. If you want to verify that your input is an integer, use <^ \ d + $>.

Excessive leading or ending spaces are often displayed in user input. You can use <^ \ s *> and <\ s * $> to match leading or ending spaces.

  • Use "^" and "$" as the beginning and end of the line to pin

If you have a string that contains multiple rows. For example, "first line \ n \ rsecond line" (where \ n \ r represents a new line character ). It is often necessary to process each line separately rather than the entire string. Therefore, almost all regular expression engines provide an option to extend the meanings of these two types of anchor. "^" Can match the start position (before f) of the string and the position (between \ n \ r and s) of each new line character ). Similarly, $ matches the end position of the string (after the last e) and the front of each new line character (between e and \ n \ r ).

In. NET, when you use the following code, it will define the anchor to match the front and back of each new line character: Regex. match ("string", "regex", RegexOptions. multiline)

Application: string str = Regex. Replace (Original, "^", ">", RegexOptions. Multiline)-inserts ">" at the beginning of each row ".

  • Absolute anchoring

<\ A> only matches the start position of the entire string, <\ Z> only matches the end position of the entire string. Even if you use the multiline mode, the <\ A> and <\ Z> do not match the new line.

Even if \ Z and $ match only the end position of the string, there is still an exception. If the string ends with a new line character, \ Z and $ match the position before the new line character, rather than the end of the entire string. This "improvement" is introduced by Perl and followed by many regular expressions, including Java and. NET. If the application is <^ [a-z] + $> to "joe \ n", the matching result is "joe" instead of "joe \ n ".

9.Word boundary

Metacharacters <\ B> are also the "anchors" that match locations ". This match is a 0-length match.

Four locations are considered as "word boundary ":

1) position before the first character of the string (if the first character of the string is a "word character ")

2) position after the last character of the string (if the last character of the string is a "word character ")

3) between a "word character" and "non-word character", the "non-word character" follows the "word character"

4) between a non-word character and a word character, the word character follows the non-word character

"Word character" is a character that can be matched with "\ w", and "non-word character" is a character that can be matched with "\ W. In most regular expression implementations, the word character usually includes <[a-zA-Z0-9 _]>.

For example, <\ b4 \ B> can match a single 4 instead of a larger part. This regular expression does not match 4 in "44.

In other words, it can be said that <\ B> matches the start and end positions of a "letter/number sequence.

The inverse set of "word boundary" is <\ B>. It is located between two "word characters" or between two "non-word characters.

  • Go deep into the regular expression engine

Let's take a look at applying the regular expression <\ bis \ B> to the string "This island is beauul UL ". The engine processes the symbol <\ B> first. Because \ B is 0, the position before the first character T will be investigated. Because T is a "word character" and the character before it is a void, \ B matches the word boundary. Next <> An error occurred while matching the first character "T. The matching process continues until the fifth space character matches the fourth character "s" <\ B>. However, space characters and <> Mismatch. Continue backward, to the sixth character "I", matched with the fifth space character <\ B>, and then < > It matches the sixth and seventh characters. However, the eighth character does not match the second "word boundary", so the match fails. It reaches 13th characters, because it forms a "word boundary" with the previous space character, at the same time < > It matches "is. The engine then tries to match the second <\ B>. Because 15th space characters and "s" form word boundaries, the match is successful. The engine is "anxious" to return the successful matching result.

10.Selector

"|" In the regular expression indicates selection. You can use the selector to match one of multiple possible regular expressions.

If you want to search for the text "cat" or "dog", you can use < >. If you want more options, you only need to expand the list < >.

The selector has the lowest priority in the regular expression, that is, it tells the engine to either match all expressions on the left of the selector or all expressions on the right. You can also use parentheses to limit the range of delimiters. For example, <\ B (cat | dog) \ B> tells the regular expression engine to process (cat | dog) as a regular expression unit.

  • Pay attention to the regular expression engine's "eager for expression"

The regular expression engine is eager to stop searching when it finds a valid match. Therefore, under certain conditions, the order of the expressions on both sides of the separator will affect the result. Suppose you want to use a regular expression to search for a list of functions in a programming language: Get, GetValue, Set or SetValue. An obvious solution is < >. Let's take a look at the result when searching for SetValue.

Because < > And < > All failed, and < > Match successful. Because the regular expression-oriented engine is "eager", it will return the first successful match, that is, "Set", rather than continuing to search for other better matches.

Contrary to our expectation, the regular expression does not match the entire string. There are several possible solutions. First, considering the urgency of the regular expression engine, it changes the order of options. for example, we use < > In this way, we can first search for the longest match. We can also combine the four options into two options: < >. Because the repeat of question marks is greedy, SetValue will always be matched before Set.

A better solution is to use the word boundary: <\ B (Get | GetValue | Set | SetValue) \ B> or <\ B (Get (Value )? | Set (Value )? \ B>. Furthermore, since all the choices have the same ending, we can optimize the regular expression to <\ B (Get | Set) (Value )? \ B>.

11.Group and backward reference

Place a part of the regular expression in parentheses, and you can group them. Then you can use some regular operations for the entire group, such as repeated operators.

Note that only parentheses () can be used to form a group. "[]" Is used to define character sets. "{}" Is used to define repeated operations.

When "()" is used to define a regular expression group, the regular expression engine will number the matched group in sequence and store it in the cache. When the group to be matched is referenced backward, it can be referenced by "\ number. <\ 1> reference the first matched back Reference Group, <\ 2> reference the second group, and so on, <\ n> references the nth group. <\ 0> references the entire matched regular expression itself. Let's look at an example.

Suppose you want to match the start tag and end tag of an HTML tag, as well as the text in the middle of the tag. For exampleThis is a test, We want to matchAndAnd text in the middle. We can use the following regular expression: '<([A-Z] [A-Z0-9] *) [^>] *> .*? "

First, "<" will match"". Then [A-Z] matches B, [A-Z0-9] * will match 0 to multiple alphanumeric characters followed by 0 to multiple non-'>' characters. The last regular expression ">" will match""> ". The regex engine will perform a inert match on the characters before the end tag until a" "

You can reference the same back-to-reference group multiple times. <([a-c]) x \ 1x \ 1> matches "axaxa", "bxbxb", and "cxcxc ". If the group referenced in the form of numbers does not have a valid match, the referenced content is empty.

A back reference cannot be used by itself. <([Abc] \ 1)> is incorrect. Therefore, you cannot use <\ 0> to match a regular expression. it can only be used in replacement operations.

Backward reference cannot be used inside the character set. <(A) [\ 1b]> <\ 1> does not indicate backward reference. <\ 1> can be interpreted as octal transcoding.

Backward reference reduces the engine speed because it needs to store matching groups. If you do not need to back-reference, you can tell the engine not to store a group. Example: < >. "(" Followed by "? : "Will tell the engine for the group (Value), does not store matching values for backward reference.

  • Repeated operations and back-reference

When the repeat operator is used for a group, the back-reference content in the cache is constantly refreshed, and only the last matched content is retained. For example, <([abc] +) = \ 1> matches "cab = cab", but <([abc]) + = \ 1> does not. Because ([abc]) when "c" is matched for the first time, "\ 1" indicates "c", and ([abc]) matches "a" and "B ". "\ 1" indicates "B", so it matches "cab = B ".

Application: check duplicate words-when editing text, it is easy to enter duplicate words, such as "". You can use <\ B (\ w +) \ s + \ 1 \ B> to detect duplicate words. To delete the second word, simply replace "\ 1" with the replacement function.

  • Group name and reference

In PHP and Python, <(? P Group)> to name the group. In this example, lexical? P Is to name the group. The name is the name of the group. You can use (? P = name.

. NET naming Group

. NET framework also supports naming groups. Unfortunately, Microsoft programmers decided to invent their own syntax instead of following the Perl and Python rules. So far, no other regular expressions have been implemented to support the syntax invented by Microsoft.

The following is an example in. NET:

(? Group )(? 'Second' group)

As you can see,. NET provides two lexical methods to create a naming group: one is to use the angle brackets "<>", or use single quotes "'' ". Angle brackets are more convenient to use in strings, and single quotes are more useful in ASP code, because "<>" is used as an HTML tag in ASP code.

To reference a naming group, use \ k Or \ k'name '.

When you replace a search, you can use "$ {name}" to reference a naming group.

12.Regular Expression Matching mode

The regular expression engine discussed in this tutorial supports three matching modes:

<> Make the regular expression case insensitive,

<> Enable "single line mode", that is, the dot "." matches the new line character.

<> Enable "multiline mode", that is, "^" and "$" match the front and back of the new line character.

  • Enable or disable the regular expression

If you insert a modifier (? Ism), the modifier only takes effect for the regular expression on the right. (? -I) disable case sensitivity. You can perform tests quickly. <(? I) te (? -I) st> it should match TEst, but cannot match teST or TEST.

13.Atomic group and prevention of backtracking

In some special cases, backtracing will make the engine extremely inefficient.

Let's take an example: to match such a string, each field in the string is separated by a comma, and the first 12th fields start with P.

We can easily think of such a regular expression <^ (.*?,) {11} P>. This regular expression works well under normal circumstances. However, in extreme cases, if the 12th fields do not start with P, catastrophic backtracking will occur. If the string to be searched is "1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ". First, the regular expression is successfully matched until it contains 12th characters. At this time, the regular expression consumes strings 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, "to the next character. <

> It does not match "12 ". Therefore, the engine performs backtracking. at this time, the regular expression consumes strings 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, and 11 ". To continue the next matching process, the next regular symbol is the dot <.>. you can match the next comma (,). However, <,> does not match "1" in the character "12 ". Matching failed. continue tracing. As you can imagine, such a backtracking combination is a very large number. Therefore, the engine may crash.

There are several solutions to prevent such huge backtracking:

A simple solution is to make matching as accurate as possible. Use the inverse character set instead of the point number. For example, we use the following regular expression <^ ([^, \ r \ n] *,) {11} P> to reduce the number of failed backtracking times to 11.

Another solution is to use an atomic group.

The purpose of an atomic group is to make the regularizedengine fail faster. Therefore, it can effectively prevent massive backtracking. The atomic group syntax is <(?> Regular expression)>. Located in (?>) All regular expressions are considered as a single regular expression. Once the match fails, the engine will go back to the regular expression section before the atomic group. In the preceding example, an atomic group can be used for table fulfillment <^ (?> (.*?,) {11}) P>. Once 12th fields match, the engine goes back to the beginning of the atomic group <^>.

14.Forward View and backward view

Perl 5 introduces two powerful regular syntax: "View forward" and "View backward ". They are also called "zero-length assertions ". They are zero-length (the so-called zero-length means that the regular expression does not consume matched strings ). The difference is that "check before and after" will actually match characters, but they will discard matching and only return matching results: matching or not matching. This is why they are called "assertions ". They do not actually consume characters in strings, but simply assert whether a matching is possible.

Almost all implementations of regular expressions discussed in this article support "viewing forward and backward ". The only exception is that Javascript only supports forward viewing.

  • Forward View of positive and negative statements

For example, if we look for a q, it is not followed by a u. That is to say, either q is not followed by a character or u is not followed. A solution for viewing forward with a negative expression is < >. The syntax for viewing the negative type forward is <(?! View content)>.

The positive view is similar to the negative view: <(? = View content)>.

If there is a group in the "View content" part, a backward reference is also generated. However, the Forward View itself does not produce a backward reference, nor is it included in the number of the backward reference. This is because the forward view itself will be discarded, and only the matching results will be retained. If you want to retain the matching result as a backward reference, you can use <(? = (Regex)> to generate a backward reference.

  • View the sequence of positive and negative statements

Backward viewing and forward viewing have the same effect, but in the opposite direction

The syntax for viewing the negative type backward is: <(? >

The syntax for positive backward viewing is: <(? <= View content)>

We can see that, compared with the forward view, there is a left angle bracket that represents the direction.

Example: <(? > It will match "B" without "a" as the leading character ".

It is worth noting that the regular expression "View" is matched from the current string position when viewing forward; the regular expression "View" is matched when viewing backward, and one character is traced back from the current string position, then, match the regular expression "View.

  • Go deep into the regular expression engine

Let's look at a simple example.

Set the regular expression < > Apply the string "Iraq ". The first symbol of the regular expression is < >. As we know, the engine is matching <> The entire string is previously scanned. After the fourth character "q" is matched, "q" is followed by a void ). The next regular symbol is to view the forward. The engine noticed that it had entered a section for viewing the regular expression forward. The next regular expression is <>, Does not match null characters, leading to a failure to match the regular expression in the forward view. Because it is a negative forward view, it means that the entire forward view result is successful. Therefore, the matching result "q" is returned.

We are applying the same regular expression to "quit ". <> "Q" is matched ". The next regular symbol is the part of the Forward View. <>. It matches the second character "I" in the string ". The engine continues to go to the next character "I ". However, the engine noticed that the forward view has been completed and the forward view has been successful. Therefore, the engine discards the matched string, which causes the engine to roll back to the character "u ".

If you want to check the forward direction, it means that the successful matching of the View part causes the entire forward view to fail. Therefore, the engine has to perform backtracking. Finally, because there are no other q and <> Match, so the entire match fails.

To ensure that you can clearly understand the implementation of the forward view, let's < > Apply it to "quit ". < > Match "q" first ". Then, check that the matching "u" is successful and the matching part is discarded. only matching judgment results are returned. The engine rolls back from the character "I" to "u ". As the forward query is successful, the engine continues to process the next regular symbol <>. Result discovery <> It does not match "u. Therefore, the matching fails. The matching of the entire regular expression fails because there is no other "q" in the end.

  • Further understanding of the internal mechanism of the regular expression engine

Let's set <(? <= A) B> apply it to thingamabob ". The engine starts to process the regular symbols and the first character in the string. In this example, the regular expression engine returns a character and checks whether "a" is matched. The engine cannot roll back because there are no characters before "t. Therefore, backward viewing fails. The engine continues to go to the next character "h ". Once again, the engine temporarily rolls back a character and checks whether "a" is matched. The result shows a "t ". An error occurred while viewing back.

Looking back, continue to fail, until the regular expression reaches the "m" in the string, so certainly backward view is matched. Because it is zero-length, the current position of the string is still "m ". The next regular expression is <>, An error occurred while matching "m. The next character is the second "a" in the string ". The engine temporarily rolls back a character and finds that <> does not match "m ".

The next character is the first "B" in the string ". The engine temporarily reverts a character and finds that it is satisfied with the backward view. at the same time, <> B is matched ". Therefore, the entire regular expression is matched. As a result, the regular expression returns the first "B" in the string ".

  • Applications viewed forward and backward

Let's look at an example of a 6-character word containing "cat.

First, we can solve the problem without looking forward and backward, for example:

<Cat \ w {3} | \ wcat \ w {2} | \ w {2} cat \ w | \ w {3} cat>

Easy enough! However, this method becomes clumsy when you need to find a word with 6-12 characters including "cat", "dog", or "mouse.

Let's take a look at the Forward View solution. In this example, we have two basic requirements: First, we need a 6-character, and second, the word contains "cat ".

The regular expression that meets the first requirement is <\ B \ w {6} \ B>. The regular expression that meets the second requirement is <\ B \ w * cat \ w * \ B>.

By combining the two, we can get the following regular expression:

<(? = \ B \ w {6} \ B) \ B \ w * cat \ w * \ B>

The specific matching process is left to the reader. However, it is important to note that forward viewing does not consume characters. Therefore, when a word is judged to meet the six-character condition, the engine will continue to match the regular expression from the beginning.

Finally, we can get the following regular expression:

<\ B (? = \ W {6} \ B) \ w {0, 3} cat \ w *>

15.Conditional test in regular expressions

The condition test syntax is <(? Ifthen | else)>. The "if" part can be a forward and backward view expression. If you use forward view, the syntax is changed to: <(? (? = Regex) then | else)>. the else part is optional.

If the if part is true, the regular expression engine tries to match the then part; otherwise, the engine tries to match the else part.

It should be noted that the forward view does not actually consume any characters, so the matching between then and else starts from the part before the if test.

16.Add comments to regular expressions

The syntax for adding comments to a regular expression is: <(? # Comment)>

For example, add a comment for a regular expression used to match a valid date:

(? # Year) (19 | 20) \ d [-/.] (? # Month) (0 [1-9] | 1 [012]) [-/.] (? # Day) (0 [1-9] | [12] [0-9] | 3 [01])

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.