Python Learning Notes-the "Fifth Week" of the basic article--Regular expressions

Source: Internet
Author: User

1 recursion problem
Import time
def Digui (N,s,num):
num + = 2
if num = = 10:
Print (s)
return s
# print (n)
# print (s)
#time. Sleep (1)
n = n + S
s = s + N
Digui (N,s,num)

ret = Digui (0,1,num=0)
Print (ret)
--------------------


Def a (n):
if n = = 0:
Return 1
Else
A (n-1)

Print a (1)
-----------------------
1) recursion is the invocation of itself in a process or function;
(2) When using a recursive strategy, there must be a definite recursive end condition called a recursive exit.

Recursive algorithms are generally used to solve three types of problems:
(1) The definition of the data is defined by recursion. (e.g. Fibonacci function)
(2) The problem solution is implemented by recursive algorithm. Back
(3) The structural form of the data is defined by recursion. (such as the traversal of trees, the search of graphs)

The disadvantage of recursion: recursive algorithm is inefficient in solving problems. In the process of recursive invocation, the system opens up a stack for each layer's return point, local quantity and so on. Too many recursion times can cause stack overflow and so on.

Def Fab (n):
If n==1:
Return 1
If n==0:
return 0
Else
Result=int (Fab (n-1)) +int (Fab (n-2))
return result

For I in range (10):
Print (Fab (i))


----------------------
2 Regular expression problems
Re.findall (' \ \ ', ' abc\com ')






----------------------
Calculator job:


Introduced
In essence, a regular expression (or RE) is a small, highly specialized programming language,
(in Python) it is embedded in Python and is implemented through the RE module.
You can specify a rule for the corresponding set of strings that you want to match, which may contain English statements,
e-mail address, Tex command, or anything you want to fix. Then you can ask, "this string
Does it match this pattern? "or" does a part of this string match the pattern? ”。 You can also make
Use RE in various ways to modify or split a string.
Character match (normal character, metacharacters):
Ordinary characters: Most characters and letters will match themselves
>>> Re.findall (' Alex ', ' Yuanalesxalexwupeiqi ')
[' Alex ']

----------------
S= ' I get A, I get B, I get C '
Re.sub ("Get", "got", s)
' I got A, I got B, I got

Subn
-------------------
S= ' I got A, I got B, I get C '
Re.split ("\s*,\s*", s)
-------------------
Re.split ("[BC]", ' abcdef ') ########?
--------------------------------------------------------------








Metacharacters:.   ^   $   *   +   ?   { }   [ ]   \   | ( )
\: Backslash followed by meta character removal special function, backslash followed by ordinary characters to achieve special functions.
\d matches any decimal number; it is equivalent to class [0-9].
\d matches any non-numeric character; it is equivalent to class [^0-9].
\s matches any whitespace character; it is equivalent to class [\t\n\r\f\v].
\s matches any non-whitespace character; it is equivalent to class [^ \t\n\r\f\v].
\w matches any alphanumeric character; it is equivalent to class [a-za-z0-9_].
\w matches any non-alphanumeric character; it is equivalent to a class [^a-za-z0-9_]
??? Re.findall (' \d.\d ', ' 5.4 ')
[]: metacharacters [] represent character classes, where only characters ^ 、-、] and \ have special meanings in a character class.
The character \ Still means escape, character-can define a range of characters, the character ^ is placed in front, indicating non.
Function:

1 Search (pattern, string[, flags]) searching for patterns in strings
2 match (pattern, string[, flags]) matches the pattern at the beginning of the string

The match object is a matching result that contains a lot of information about this match and can be obtained using the readable properties or methods provided by match.

Property:

String: The text to use when matching.
Re: The pattern object to use when matching.
POS: The index in which the text expression begins the search. The value is the same as the parameter with the same name as the Pattern.match () and Pattern.seach () methods.
Endpos: The index of the end-of-search text expression. The value is the same as the parameter with the same name as the Pattern.match () and Pattern.seach () methods.
Lastindex: The index of the last captured grouping in the text. If there are no captured groupings, it will be none.
Lastgroup: The alias of the last captured group. If the group has no aliases or no captured groupings, it will be none.
Method:

Group ([Group1, ...]):
Gets the string that is intercepted by one or more groups, and returns a tuple when multiple parameters are specified. Group1 can use numbers or aliases; number 0 represents the entire matched substring; returns Group (0) when no parameters are filled; Groups that have not intercepted a string return none; The group that intercepted multiple times returns the last substring intercepted.
Groups ([default]):
Returns the string intercepted by all groups as a tuple. Equivalent to calling group (,... last). Default indicates that a group that does not intercept a string is replaced with this value, which defaults to none.
Groupdict ([default]):
Returns a dictionary with aliases for the alias of the group, the value of the substring intercepted by the group, and no alias for the group. The default meaning is the same.
Start ([group]):
Returns the starting index of the substring intercepted by the specified group in string (the index of the first character of the substring). The group default value is 0.
End ([group]):
Returns the end index of the substring intercepted by the specified group in string (the index of the last character of the substring + 1). The group default value is 0.
span ([group]):
Return (Start (group), End (group))
3 split (rule, Target [, maxsplit]) splits strings based on pattern matches
4 FindAll (pattern, string) lists all occurrences of a pattern in a string
5 Sub (rule, replace, Target [, Count])
6 Finditer (pattern, string) return iterator
7 compile (pattern[, flags]) create a Pattern object from a string containing a regular expression
>>> Import re
>>> Re.match ("C", "abcdef")
>>> Re.search ("C", "abcdef")
<_sre. Sre_match Object at 0x00a9a988>

>>> Re.match ("C", "Cabcdef")
<_sre. Sre_match Object at 0x00a9ab80>

>>> Re.search ("C", "Cabcdef")
<_sre. Sre_match Object at 0x00af1720>

>>> patterm = Re.compile ("C")
>>> Patterm.match ("abcdef")
>>> Patterm.match ("abcdef", 1)
>>> Patterm.match ("ABCdef", 2)
<_sre. Sre_match object; Span= (2, 3), match= ' C ' >


-------------
Group ([Index|id]) Gets the matching group, which returns the set 0 by default, which is the full value
Groups () returns all the groups
Groupdict () returns a dictionary of values with the group name key, matching content
Next Example:
>>> M.groupindex ()
{' Age ': ' + ', ' tel ': ' 88888888 ', ' name ': ' Tom '}
Start ([group]) Gets the starting position of the matching group
End ([group]) Gets the end position of the matched group
span ([group]) Gets the (start, end) position of the matching group











Trouble line break!!! -----------------------------------------------------------------------------------


The regular expression uses the backslash "\" to represent a special form or as an escape character, which conflicts with the syntax of Python, so
Python uses "\\\\" to denote "\" in the regular expression, because if you want to match "\" in the regular expression, you need to use \ to go
Meaning, "\ \", and the Python syntax \ is also a special character, if you want to express the pure \, you have to escape, that is, each of the string must be escaped
So it becomes the "\\\\".
In order to make the regular expression more readable, Python specifically designed the original string (raw string),
Raw string (suppress escaping) is the prefix of the string with ' R ',
such as r "\ n": two characters "\" and "n" instead of line breaks. This form is recommended when writing regular expressions in Python.
>>> re.findall (' \ \ ', ' abc\com ')
Traceback (most recent)

>>> re.findall (' \\\\ ', ' abc\com ')
[‘\\‘]
>>> re.findall (r ' \ \ ', ' abc\com ')
[‘\\‘]

Note: The string represented by R ' is called the raw string and is used to suppress escaping. The regular expression uses the backslash (\) to escape special characters so that they can match the character itself rather than specifying other special meanings. This may conflict with the literal string escape of Python, which may be confusing. For example, to match a backslash itself, you might want to use ' \\\\ ' as a string for the regular expression, because if the regular expression is \ \, and the string, each backslash is written \ \. You can also avoid partial confusion by prefixing the string with R, because the python string that starts with R is the raw string, so all the characters inside are not escaped, such as R ' \ n ', which is a backslash plus a letter n, and ' \ n ' We know it's a newline character. Therefore, the above ' \\\\ ' You can also write R ' \ \ ', so that it should be good to understand a lot.















Python Learning Notes-the "Fifth Week" of the basic article--Regular expressions

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.