Regular ExpressionsApplication Scenarios
-
Search for a particular pattern string, replace cut, etc.
-
Validation of formats such as mailbox formats, URLs, etc.
-
Crawler projects to extract specific valid content
-
Configuration files for many applications
Principles of Use
-
Do not use regular as long as it can be solved by related functions such as strings.
-
Regular execution efficiency is lower, which reduces the readability of the Code
-
The world's most difficult to read three things: the Doctor's prescription, the priest's divine symbol, the code farmer's regular
-
Remind: Regular is used to write, not to read, do not try to read others ' regular, do not understand the function when necessary to read the regular.
Basic Use
Regular Rules
-
Single character
Normal character: one-to-one exact match
[]: Any one of the characters in the middle
[A-z]: Any character representing A to Z
[0-9]: Any character representing 0 to 9
[^ABC]: characters other than ABC
. : matches any character other than ' \ n '
\d: All numeric characters, equivalent to [0-9]
\d: All non-numeric characters, equivalent to [^0-9]
\w: All numbers, letters, Chinese, underscores, etc. (meaning of the word)
All characters except the \w:\w
\s: All whitespace characters, such as: space, \ t, \ n, \ r
All characters except the \s:\s
\b: Word boundaries, such as: opening, ending, punctuation, spaces, etc.
\b: Non-word boundary
-
Frequency control
*: The preceding character can be any time
+: The preceding character appears at least once
?: At most one time, 0 or 1 times
{m}: matches fixed M-Times
{m,}: at least m times
{M,n}:m to n times
Regular matches are greedy by default.
-
Boundary limit
ImportRe
?
# start with the specified content
# C = re.compile (R ' ^abc ')
# to specify end of content
Span class= "Cm-comment" ># C = re.compile (R ' abc$ ')
# also limits the beginning and end of
c = re. Compile (r ' ^abc$ ')
?
s = c.search ( ' abc ')
?
if s:
Print ( "OK")
print ( s.group ())
-
Group Matching
-
|: Represents or, with the lowest priority
-
(): Used to represent a whole, can determine priority
import re
?
# | represents or, with the lowest priority
# () is used to represent a whole, which can be determined by priority
Span class= "cm-variable" >c = re. Compile (r ' A (hello|world) d ')
?
s = c.search ( ' aworldd ')
?
if s:
Print ( "OK")
print ( s.group ())
() There is also the role of group matching, next time.
Practice:
-
What to do if you match a character with a special regular meaning, such as: \d
-
Verify that a string is the correct mailbox format
-
Verify that a string is the correct URL format
Ideas
-
Function-oriented
-
Write out several strings that match the rules
-
Write a little bit of measurement, keep adjusting.
-
Final Completion function
Python Regular Expressions