Python regular expression,
Python Regular Expression
An atom is the most basic unit in a regular expression. Each regular expression contains at least one atom. Common atomic types include common characters as atoms, non-printable characters as atoms, and general characters as atoms and atomic tables. The re module must be called for use.
1. Use common characters as atoms
Eg: import re
String = "taoyunjioayu"
Pat = "yun"
Rst = re. search (pat, string)
Print (rst)
Ii. Non-printable characters as atoms
Eg: \ n linefeed \ t Tab
Import re
String = ''' taoyunjiaoyu '''
Pat = "\ n"
Rst = re. search (pat, string)
Print (rst)
3. Use common characters as atoms
\ W: represents any letter, number, or underline
\ W: represents any non-letter, number, or underline
\ D: represents a decimal number
\ D: represents any decimal number
\ S: white space characters
\ S: Except for white space characters
4. Atomic table
Several atoms are placed in [] to form an atomic table. Each atom in an atomic table is equal. Indicates to extract any atom from the atomic table.
Eg: [sdk]
Extract any one of the s, d, and k atoms from the string.
String = "djfhdkgsdk"
Pat = "kg [sdk]"
Rst = re. seach (pat, string)
Print (rst)
Running result: kgs
5. metacharacters
Metacharacters are special characters in regular expressions, such as repeating the characters before N times.
(1). match any character except the line break (called "wildcard ")
(2)...: Fuzzy match
(3) ^: match the start position
(4) $: matching end position
(5) *: Repeated matching
(6 )? : Match appears 0 or 1 time
(7) +: Match appears once to multiple times
(8) {n}: Exactly n times
(9) {n, m}: appears at least n times, appears at most m times
(10) |: Mode selector or
(11) (): Mode Unit
* Equivalent to {0, positive infinity} + equivalent to {1 ,}? Equivalent to {0, 1}
6. Pattern Modifier
Eg: rst = "re. search (pat, string, re. I )"
Note: pat is a regular expression, string is a data source, and I is a pattern modifier.
(1) case insensitive for I matching
(2) M multi-row matching
(3) L localized matching recognition
(4) U unicode matching
(5) S. Match includes line breaks
VII. Regular Expression Functions
1. re. match: match from the beginning
2. re. search: matching can be performed anywhere and can only be performed once. (after a successful match is performed, the matching is not followed, but the result is directly output)
3. Global matching function: re. compile (Regular Expression). findall (data)
4. re. sub (): Used to replace strings.
Re. sub (Regular Expression, replaced by content, source data)