Home >Backend Development >Python Tutorial >Python's re module regular expression operations

Python's re module regular expression operations

高洛峰
高洛峰Original
2017-03-02 16:08:141236browse

This module provides regular expression matching operations similar to Perl. The same applies to Unicode strings.

Regular expressions use backslash "\" to represent special forms or as escape characters. This conflicts with Python's syntax. Therefore, Python uses "\\\\" to represent regular expressions. "\" in the formula, because if you want to match "\" in the regular expression, you need to use \ to escape it and become "\\", and in Python syntax, you need to escape every \ in the string. So it becomes "\\\\".

Do you find the above writing method troublesome? In order to make regular expressions more readable, Python specially designed raw strings. I need to remind you that in Don't use raw string when writing file paths, there are pitfalls here. Raw string uses 'r' as the prefix of the string, such as r"\n": it represents the two characters "\" and "n" instead of the newline character. This form is recommended when writing regular expressions in Python.

Most regular expression operations can achieve the same purpose as module-level functions or RegexObject methods. And it doesn't require you to compile the regular expression object from the beginning, but you can't use some practical fine-tuning parameters.

1. Regular expression syntax

In order to save space, it will not be described here.

2. The difference between march and search

Python provides two different primitive operations: match and search . Match starts from the starting point of the string, while search (perl default) starts any match from the string.

Note: When the regular expression starts with '^', match and search are the same. match will succeed only if and only if the matched string can be matched from the beginning or can be matched starting from the position of the pos parameter. As follows:

>>> 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 at 0x00A9AB80>

##3.Module content

re.compile(pattern, flags=0)


Compile the regular expression and return the RegexObject object, and then you can call match() and search() through the RegexObject object method.


prog = re.compile(pattern)

result = prog.match(string)

followed by


result = re .match(pattern, string)


is equivalent.


The first method can realize the reuse of regular expressions.


re.search(pattern, string, flags=0)

Search in the string to see if it can match the regular expression. Returns a _sre.SRE_Match object, or None if no match is found.


re.match(pattern, string, flags=0)

Whether the beginning of the string can match the regular expression. Returns a _sre.SRE_Match object, or None if no match is found.


re.split(pattern, string, maxsplit=0)

Split the string through regular expressions. If you enclose the regular expression in parentheses, the matching string will also be included in the list and returned. maxsplit is the number of separations, maxsplit=1 separates once, the default is 0, and there is no limit on the number of times.


>>> re.split('\W+', 'Words, words, words.')

['Words', 'words', 'words', ' ']
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ' , 'words', '.', '']
>>> re.split('\W+', 'Words, words, words.', 1)
['Words', ' words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)

Note: I used Python is 2.6. Looking at the source code, I found that split() does not have the flags parameter. It was added in 2.7. I have found this problem more than once. The official documentation is inconsistent with the source code. If you find an abnormality, you should go to the source code to find the reason.


If there is a match at the beginning or end of the string, the returned list will start or end with an empty string.


>>> re.split('(\W+)', '...words, words...')
['', '...', 'words', ' , ', 'words', '...', '']

If the string cannot match, the list of the entire string will be returned.

>>> re.split("a","bbb")
['bbb']

re.findall (pattern, string, flags=0)

Find all substrings matched by RE and return them as a list. The matches are returned in order from left to right. If there is no match, an empty list is returned.

>>> re.findall("a","bcdef")
[]

>>> re.findall (r"\d+","12a32bc43jf3")
['12', '32', '43', '3']

re.finditer(pattern, string, flags= 0)

Find all substrings matched by RE and return them as an iterator. The matches are returned in order from left to right. If there is no match, an empty list is returned.

>>> it = re.finditer(r"\d+","12a32bc43jf3")
>>> for match in it:
print match .group()

re.sub(pattern, repl, string, count=0, flags=0)

Find all substrings matched by RE and use a Different string replacements. The optional argument count is the maximum number of substitutions after a pattern match; count must be a nonnegative integer. The default value is 0 which replaces all matches. If there is no match, the string will be returned unchanged.

re.subn(pattern, repl, string, count=0, flags=0)

has the same effect as the re.sub method, but returns a new A two-tuple of string and number of replacement executions.

re.escape(string)

Escape non-alphanumeric characters in the string

re.purge()

Clear the regular expressions in the cache

4. Regular expression object

re.RegexObject

re.compile() returns the RegexObject object

re.MatchObject

group() returns the object matched by RE String

start() returns the position where the match starts

end() returns the position where the match ends

span() returns a Tuple containing the position of the match (start, end)

5. Compilation flags

Compilation flags allow you to Modify some of the ways regular expressions operate. In the re module, the flag can use two names, one is the full name such as IGNORECASE, and the other is the abbreviation, one-letter form such as I. (If you're familiar with Perl's mode modification, the one-letter forms use the same letter; for example, the abbreviation for re.VERBOSE is re.X.) Multiple flags can be specified by bitwise OR-ing them. For example, re.I | re.M is set to I and M flags:

I
IGNORECASE

Make matching case matching Insensitive; character classes and strings ignore case when matching letters. For example, [A-Z] can also match lowercase letters, and Spam can match "Spam", "spam", or "spAM". This lowercase letter does not take into account the current position.

L
LOCALE

Affects "w, "W, "b, and "B, depending on the current localization set up.

locales is a feature in the C library that is used to assist programming where different languages ​​need to be considered. For example, if you're working with French text, you want to match text with "w+, but "w only matches the character class [A-Za-z]; it doesn't match "é" or "?". If your system is configured appropriately and the locale is set to French, an internal C function will tell the program that "é" should also be considered a letter. Using the LOCALE flag when compiling a regular expression will result in a compiled object that uses these C functions to handle "w"; this will be slower, but will also allow you to use "w+ to match French text.

M
MULTILINE

(^ and $ will not be interpreted at this time; they will be introduced in Section 4.1.)

Use "^" to match only the beginning of the string, while $ will only match the end of the string and the end of the string immediately before a newline (if any). When this flag is specified, "^" matches the beginning of the string and the beginning of each line in the string. Likewise, the $ metacharacter matches the end of the string and the end of each line in the string (directly before each newline).

S ​​
DOTALL

Causes the "." special character to match exactly any character, including newlines; without this flag, "." Matches any character except newline.

X
VERBOSE

This flag makes writing regular expressions easier to understand by giving you a more flexible format. When this flag is specified, whitespace within the RE string is ignored unless the whitespace is within a character class or after a backslash; this allows you to organize and indent REs more clearly. It also allows you to write comments to the RE, which will be ignored by the engine; comments are marked with a "#" symbol, but this symbol cannot come after a string or a backslash.

Finally: If you can use the string method, don’t choose regular expressions, because the string method is simpler and faster.

For more articles related to Python’s re module regular expression operations, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn