Python Regular expression (escape problem) _python

Source: Internet
Author: User

Let's talk about a rather embarrassing thing: in writing the shrimp music to listen to the download device encountered a problem, because the saved files are named after the title of the music, so encountered some such as "impose zhi/out border", etc. contain illegal characters (hem, said you →_→ Windows) of the title, will save the failure. So I remembered the solution of the Thunderbolt: to replace all the illegal characters into underscores.

Thus, the use of regular expressions is introduced. After a search was swallowed, I wrote down such a function:

Copy Code code as follows:

def sanitize_filename (filename):
return Re.sub (' [\/:*? <>|] ', ' _ ', filename)

I've recently been aware of many of the problems in this function:

    • Python and Shell are different, regardless of single or double quotes, the backslash is an escape character. The dog's luck is that Python's handling of meaningless escapes \/ remains intact.
    • Even so, sanitize_filename('\\/:*?<>|') The return \_______ rather than all is underlined.

So I feel turkey to look at the document.

Raw strings

After reading the document, I realized that the escape of the Python regular expression module was independent. For example, matching a backslash character requires the argument to be written: ' \\\\ ':

Python escapes string: \\\\ is escaped as \ \
The RE module gets the incoming \ \ Interprets it as a regular expression and escapes the regular expression with the escape rule to \
With such trouble, Raw string is a big thing, as the name implies (except the trailing backslash) that will not be escaped. So matching a backslash character can write R ' \ '.

So the above Sanitize_filename changed to:

Copy Code code as follows:

def sanitize_filename (filename):
Return Re.sub (R ' [\\/:*? <>|] ', ' _ ', filename)

Regex and Match

So seriously look at the RE module bar ~ below for the flow account, for the impatient to watch.

Python's regular expression module the main object in the RE is actually these two:

Regular Expression Regexobject
Matching Matchobject
Regexobject is a regular expression object, and all operations such as match sub are owned by it. Generated by re.compile (pattern, flag).

Copy Code code as follows:

>>> Email_pattern = re.compile (R ' \w+@\w+\.\w+ ')
>>> Email_pattern.findall (' My email was abc@def.com and his's is user@example.com ')
[' abc@def.com ', ' user@example.com ']

One of the ways:

Search matches from any character, returning Matchobject or None
Match starts with the first character and returns Matchobject or None
Split returns the List by matching the split
FindAll returns all matching List
Finditr returns the Matchobject iterator
Sub returns the replaced string
SUBN return (replacement string, number of replacements)
The functions provided in the RE module, such as Re.sub Re.match Re.findall, can actually be considered as a shortcut to eliminating the direct creation of regular expression objects. And because the Regexobject object itself can be reused, this is the advantage of its relative to these shortcut functions.

Matchobject is a matching object that represents the result of a regular expression match. Returned by some methods of Regexobject. The matching object is always True, and there is a whole bunch of ways to get information about grouping (group) in regular expressions.

Copy Code code as follows:

>>> for M in Re.finditer (R ' (\w+) @\w+\.\w+ ', ' my email are abc@def.com and his is user@example.com '):
... print '%d-%d%s '% (M.start (0), m.end (0), M.group (1), M.group (0))
...
12-23 ABC abc@def.com
35-51 User user@example.com

Reference

    • The Python Standard Library: http://docs.python.org/2/library/re.html

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.