Python -- Regular Expression (5)

Source: Internet
Author: User

Python -- Regular Expression (5)

6. FAQs
Regular Expressions are very powerful tools in applications, but sometimes they cannot be executed intuitively as you wish. This section describes some common problems with using regular expressions.

Certificate ------------------------------------------------------------------------------------------------------------------------------------------------------

6. 1. Use the string method
Sometimes using the re module is an error. If you want to match a fixed string or a separate character class, and you do not use any re module flag, such as IGNORECASE, then you do not need a regular expression. Python strings have some methods to operate fixed strings. They are usually faster, because they are implemented through a small loop of optimized C language, rather than a more general Regular Expression Engine.

Here is an example of replacing a fixed string. For example, you want to replace word with deed. Re. sub () seems to be able to do this, but it still uses the string replace () method directly. Note that the replace () method also replaces the word string in the middle of the word. For example, swordfish is replaced with sdeedfish, and the simple regular expression word is also used. To avoid replacing the word substring in the middle of a word, you must use the regular expression pattern \ bword \ B to determine the word boundary on both sides of the word. This requires a regular expression, because it is beyond the functional scope of the replace () function.

Another common task is to delete a single character from a string or replace it with another character. You may use re. sub ('\ n', '', S), but the string's translata () method can do the same job and usually run faster than the regular expression.

In short, before using the re module, consider whether your problem can be solved through faster and simpler string functions.

Certificate ------------------------------------------------------------------------------------------------------------------------------------------------------

6.2.match () VS search ()
The match () method only matches strings at the beginning, while the search () method scans the entire string to check whether a matching string exists. It is important to remember the difference. Once again, the match () method only reports a match whose start position is 0 once. If the start position of the match is not 0, the match () method does not report it.

>>> print(re.match('super','superstition').span())(0, 5)>>> print(re.match('super','insuperable'))None
The search () method scans the entire string and then reports the first match it finds:
>>> print(re.search('super','superstition').span())(0, 5)>>> print(re.search('super','insuperable').span())(2, 7)
Sometimes you may venture to use re. match () and add '. *' to the front of the RE. It is best not to do this, but to use re. search (). The Regular Expression Engine analyzes regular expressions to accelerate matching execution. In general, the analysis will first find out what the first matched character is. For example, a pattern starting with Crow must start with character C, after analysis, the matching engine quickly scans the string to find the character C and starts matching all the characters after the character C is found.

Therefore, adding '. *' will cause the optimization to fail. This requires scanning from start to end, and then matching the remaining part of the RE. Therefore, it is best to use re. search ().
Certificate ------------------------------------------------------------------------------------------------------------------------------------------------------

6. 3. Greedy VS non-greedy
When you repeat a regular expression, such as a *, the result is as many matches as possible. This result may hurt you sometimes, especially when you match a pair of delimiters. For example, HTML tags enclosed by Angle brackets. Due to the repeated greedy nature of asterisks, an error occurs when regular expressions match a single HTML Tag.

>>> s = '
'>>> Len (s) 32 >>> print (re. match ('<. *> ', s ). span () (0, 32) >>> print (re. match ('<. *> ', s ). group ()) The regular expression matches the left brackets in the regular expression <, and then. * greedily matches all the remaining characters. At this time, the right brackets in the regular expression> cannot match at the end of the string. Therefore, the matching engine returns one character, until it finds matching the last right brace>. The final matching result is the content between the left and right brackets, but this is not the result you want.

In this case, the solution is to use non-Greedy symbols *? , +? ,?? Or {m, n }?, These characters match as much text as possible. In the preceding example, The right brace> tries to match immediately after the first left brace <match. If the match fails, the matching engine will forward a character down, each step is retried until the match is successful or to the end of the string. Then we can get the expected results:
>>> print(re.match('<.*?>',s).group())
Note: using regular expressions to analyze HTML or XML is very painful. The regular expressions you write can handle some common situations, but HTML and XML always break the rules. Therefore, when you write a regular expression to handle all possible situations, this regular expression will be very complex. In this case, we recommend that you use the HTML and XML Parser for better processing.

Certificate ------------------------------------------------------------------------------------------------------------------------------------------------------

6. 4. Use re. VERBOSE
Now you have noticed that regular expressions are a compact method, but they are very difficult to read. A moderately complex regular expression contains many backslash, Parentheses, and metacharacters, which makes it difficult to read and understand.

For such a regular expression, specifying the re. VERBOSE flag during compilation is helpful because it allows you to organize the regular expression more clearly.

The re. VERBOSE flag has several effects. Spaces in regular expressions are ignored if they are not in character classes, which means regular expressions like dog | cat have the same meaning as those with poor readability, however, the character class [a B] Still matches characters a, B, or a space. In addition, you can also write comments in a regular expression. The comments are the content from # To the next line. When a string is enclosed in three quotes, the regular expression becomes more concise.

pat = re.compile(r'''\s*               #Skip leading whitespace(?P
[^:] +) # Header name \ s *: # Whitespace, and a colon (? P .*?) # The header's value --*? Used to # lose the following trailing whitespace \ s * $ # Trailing whitespace to end-of-line ''', re. VERBOSE) This is much clearer than what is written below:
pat = re.compile(r'\s*(?P
[^:] +) \ S *:(? P .*?) \ S * $ ')

 

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.