Python Regular Expression knowledge summary, python Regular Expression

Source: Internet
Author: User

Python Regular Expression knowledge summary, python Regular Expression

1. Regular expression syntax

1.1 characters and character classes
1 Special Character: \. ^ $? + * {} [] () |
To use the literal value for the preceding special characters, use \ to escape the character.
2 character class
1. One or more characters contained in [] are called character classes. When a character class matches, if no quantifiers are specified, only one of them will be matched.
2. a range can be specified within the character class, for example, [a-zA-Z0-9] represents any character between A to z, a to Z, 0 to 9
3. The left square brackets follow a ^ to deny a character class. For example, [^ 0-9] indicates matching any non-numeric character.
4. In the character class, except \, other special characters do not have any special meaning and all represent the literal value. ^ If it is placed in the first position, it indicates no. If it is placed in another position, it indicates ^ itself.-If it is placed in the middle, it indicates the range. If it is placed in the first character class, it indicates-itself.

5. the stenographer can be used inside the character class, for example, \ d \ s \ w.
3 stenography
. It can match any character except the line break. If the re. DOTALL sign exists, it will match any character including line break.
\ D matches a Unicode number. If it contains re. ASCII, it matches 0-9.
\ D match Unicode non-Numbers
\ S matches Unicode white space. If it contains re. ASCII, it matches one of \ t \ n \ r \ f \ v.
\ S match Unicode non-Blank
\ W matches Unicode word characters, and if it carries re. ascii, matches one of [a-zA-Z0-9 _]
\ W matches Unicode non-single-byte characters

1.2 quantifiers
1 .? Match the first character 0 or 1 time
2. * match the previous character 0 or multiple times
3. + match the previous character once or multiple times
4. {m} matches the previous expression m times
5. {m,} matches the previous expression at least m times
6. {, n} matches the regular expression n times at most.
7. {m, n} matches the regular expression at least m times and at most n times
Note:
All of the above quantifiers are in greedy mode and will match as much as possible. If you want to change to non-Greedy mode, follow one of them after the quantifiers? To achieve

1.3 group and capture
1:
1. Capture the content of the Regular Expression in () for further exploitation. You can follow? : To disable the bracket capture function
2. Combine part of the regular expression to use quantifiers or |
2. The response references the content captured in the previous:
1. Reverse reference by group number
Every one is not used? : The parentheses are all allocated with a group, starting from 1 and increasing from left to right. You can use \ I to reference the content captured by the previous () expression.
2. Use the group name to reverse reference the content captured in the parentheses
Can be followed? P <name>, put the group name in the angle brackets to create an alias for a group, followed (? P = name) to reference the previously captured content. For example (? P <word> \ w +) \ s + (? P = word) to match duplicate words.
3. Notes:
Reverse references cannot be placed in character classes.

1.4 assertions and tags
Assertions do not match any text, but impose certain constraints on the text where the assertions are located.
1 Common assertions:
1. \ B matches the boundary of a word. In the character class [], it indicates backspace.
2. \ B matching non-word boundary, affected by ASCII mark
3. \ A matches at the start
4. ^ match at the beginning. If the MULTILINE flag exists, match after each line break.
5. \ Z match at the end
6. $ match at the end. If the MULTILINE flag exists, match before each line break.
7 .(? = E) Forward Looking
8 .(?! E) Negative foresight
9 .(? <= E) Reviewing
10 .(? <! E) negative review
2. Explanation of forward-looking review
Prospective: exp1 (? = Exp2) the content after exp1 must match exp2.
Negative Foresight: exp1 (?! Exp2) the content after exp1 cannot match exp2
Postcare :(? <= Exp2) the content before exp1 exp1 must match exp2.
Negative care :(? <! Exp2) exp1 exp1 content cannot match exp2
For example, we want to search for "hello", but "hello" must be followed by "world". The regular expression can be written as follows: "(hello) \ s + (? = World) ", used to match" hello wangxing "and" hello world "can only match the latter's hello

1.5 condition matching
(? (Id) yes_exp | no_exp): If the subexpression of the corresponding id matches the content, yes_exp is matched here; otherwise, no_exp is matched.

1.6 regular expression flag
1. There are two ways to use the regular expression flag.
1. pass in the flag parameter to the compile method. Multiple flags use the | split method, such as re. compile (r "# [\ da-f] {6} \ B", re. IGNORECASE | re. MULTILINE)
2. Add (? Sign) method to add a sign to a regular expression, such (? MS) # [\ da-z] {6} \ B
2. Common Signs
Re. A or re. ASCII so that \ B \ B \ s \ S \ w \ W \ d \ D assume that the string is assumed that the string is ASCII
Re. I or re. IGNORECASE make the regular expression case-insensitive
Re. M or re. MULTILINE match multiple rows so that each ^ matches each $ after each carriage return and before each carriage return.
Re. S or re. DOTALL enables. to match any character, including carriage return.
Re. X or re. VERBOSE can span multiple rows in the regular expression, or add comments, but the blank space must be expressed by \ s or [], because the default blank space is not explained. For example:
Re. compile (r """
[^>] *? # Not An src attribute
Src = # Start of the src attribute
(? :
(? P <quote> ["']) # Left quotation marks
(? P <image_name> [^ \ 1>] + ?) # Image name
(? P = quote) # parentheses
", Re. VERBOSE | re. IGNORECASE)

2. Python Regular Expression Module

2.1 Regular Expressions process strings with four main functions

1. check whether a string matches the regular expression syntax. Generally, true or false is returned.
2. Obtain a regular expression to extract the required text from the string.
3. Replace the text matching the regular expression in the search string with the corresponding string
4. Use a regular expression to separate strings.

2.2 In Python, the re module uses regular expressions in two ways

1. Use the re. compile (r, f) method to generate a regular expression object, and then call the corresponding method of the regular expression object. This method can be used multiple times after a regular object is generated.
2. In the re module, each object method of the regular expression object has a corresponding module method. The only difference is that the first parameter passed in is the regular expression string. This method is suitable for using only one regular expression.

2.3 common methods for regular expression objects

1. rx. findall (s, start, end ):
Returns a list. If there is no group in the regular expression, the list contains all matched content,
If a regular expression contains a group, each element in the list is a tuple, which contains the content matched in the sub-group, but does not return the content matched by the entire regular expression.
2. rx. finditer (s, start, end ):
Returns an iteratable object.
Iterates an object that can be iterated. Each time a matching object is returned, you can call the group () method of the matching object to view the content matched by the specified group. 0 indicates the content matched by the entire regular expression.
3. rx. search (s, start, end ):
Returns a matched object. If no matching is found, None is returned.
The search method is stopped only once and will not continue to be matched later.
4. rx. match (s, start, end ):
If the regular expression matches at the start of the string, a matching object is returned. Otherwise, None is returned.
5. rx. sub (x, s, m ):
Returns a string. X is used to replace each matched string. The replaced string is returned. If m is specified, m is replaced at most. For x, you can use/I or/g <id> id to reference the captured content by group name or number.
The x in the module method re. sub (r, x, s, m) can use a function. In this case, we can push this function to the captured content before replacing the matched text.
6. rx. subn (x, s, m ):
The same as the re. sub () method, the difference is that a binary group is returned, one of which is the result string and the other is the number of replicas.
7. rx. split (s, m): split string
Back to a list
Use the content matched by the regular expression to split the string
If a regular expression contains a group, the content matched by the Group is placed in the middle of each of the two shards in the list as part of the list, for example:
Rx = re. compile (r "(\ d) [a-z] + (\ d )")
S = "ab12dk3klj8jk9jks5"
Result = rx. split (s)
Return ['ab1', '2', '3', 'klj', '8', '9', 'jks5 ']
8. rx. flags (): indicates the flag set during regular expression compilation.
9. rx. pattern (): string used for regular expression Compilation

2.4 attributes and methods of matching objects

01. m. group (g ,...)
Returns the content matched by the number or group name. By default, or 0 indicates the content matched by the entire expression. If multiple matches are specified, a single tuples are returned.
02. m. groupdict (default)
Returns a dictionary. The dictionary key is the group name of all named groups. The value is the content captured by the naming group.
If the default parameter exists, it is used as the default value for those groups that are not involved in the matching.
03. m. groups (default)
Returns a tuple. Contains all the sub-groups that have captured the content. Starting from 1, if the default value is specified, this value is used as the values of those groups that have not captured the content.
04. m. lastgroup ()
The name of the capture group with the highest number matching the content. If no or no name is used, None is returned (not commonly used)
05. m. lastindex ()
The number of the capture group with the highest content number. If not, None is returned.
06. m. start (g ):
The Child Group of the currently matched object starts matching from the position of the string. If the current group is not involved in the match, the system returns-1.
07. m. end (g)
The sub-group of the currently matched object ends from the position of the string. If the current group is not involved in the match,-1 is returned.
08. m. span ()
Returns a binary group with the returned values of m. start (g) and m. end (g ).
09. m. re ()
Generate the regular expression of the matching object
10. m. string ()
String passed to match or search for matching
11. m. pos ()
The start position of the search. That is, the start of a string or the position specified by start (not commonly used)
12. m. endpos ()
The end position of the search. That is, the end position of the string or the position specified by the end (not commonly used)

2.5 Conclusion

1. For the regular expression matching function, Python does not return the true or false methods, but you can determine whether the return value of the match or search method is None.
2. For the regular expression search function, you can use the match object returned by the search or match method only once to obtain the matching object. for multiple searches, you can use the iteratable object returned by the finditer Method for iterative access.
3. to replace a regular expression, you can use the sub or subn method of the regular expression object or the re module method sub or subn, the difference is that a function can be used to generate the replacement text of the sub method of the module.
4. You can use the split method of the regular expression object to split the regular expression. Note that if the regular expression object has a group, the content captured by the group will also be placed in the returned list.

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.