Hướng dẫn python regular expression hyphen - dấu gạch nối biểu thức chính quy python

This module provides regular expression matching operations similar to those found in Perl.

Both patterns and strings to be searched can be Unicode strings as well as 8-bit strings. However, Unicode strings and 8-bit strings cannot be mixed: that is, you cannot match an Unicode string with a byte pattern or vice-versa; similarly, when asking for a substitution, the replacement string must be of the same type as both the pattern and the search string.

Regular expressions use the backslash character ['\'] to indicate special forms or to allow special characters to be used without invoking their special meaning. This collides with Python’s usage of the same character for the same purpose in string literals; for example, to match a literal backslash, one might have to write '\\\\' as the pattern string, because the regular expression must be \\, and each backslash must be expressed as \\ inside a regular Python string literal.

The solution is to use Python’s raw string notation for regular expression patterns; backslashes are not handled in any special way in a string literal prefixed with 'r'. So r"\n" is a two-character string containing '\' and 'n', while "\n" is a one-character string containing a newline. Usually patterns will be expressed in Python code using this raw string notation.

It is important to note that most regular expression operations are available as module-level functions and methods on compiled regular expressions. The functions are shortcuts that don’t require you to compile a regex object first, but miss some fine-tuning parameters.

See also

Mastering Regular ExpressionsBook on regular expressions by Jeffrey Friedl, published by O’Reilly. The second edition of the book no longer covers Python at all, but the first edition covered writing good regular expression patterns in great detail.

6.2.1. Regular Expression Syntax¶

A regular expression [or RE] specifies a set of strings that matches it; the functions in this module let you check if a particular string matches a given regular expression [or if a given regular expression matches a particular string, which comes down to the same thing].

Regular expressions can be concatenated to form new regular expressions; if A and B are both regular expressions, then AB is also a regular expression. In general, if a string p matches A and another string q matches B, the string pq will match AB. This holds unless A or B contain low precedence operations; boundary conditions between A and B; or have numbered group references. Thus, complex expressions can easily be constructed from simpler primitive expressions like the ones described here. For details of the theory and implementation of regular expressions, consult the Friedl book referenced above, or almost any textbook about compiler construction.

A brief explanation of the format of regular expressions follows. For further information and a gentler presentation, consult the Regular Expression HOWTO.

Regular expressions can contain both special and ordinary characters. Most ordinary characters, like 'A', 'a', or '0', are the simplest regular expressions; they simply match themselves. You can concatenate ordinary characters, so last matches the string 'last'. [In the rest of this section, we’ll write RE’s in this special style, usually without quotes, and strings to be matched 'in single quotes'.]

Some characters, like '|' or '[', are special. Special characters either stand for classes of ordinary characters, or affect how the regular expressions around them are interpreted. Regular expression pattern strings may not contain null bytes, but can specify the null byte using a \number notation such as '\x00'.

The special characters are:

'.'[Dot.] In the default mode, this matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline.'^'[Caret.] Matches the start of the string, and in MULTILINE mode also matches immediately after each newline.'$' Matches the end of the string or just before the newline at the end of the string, and in MULTILINE mode also matches before a newline. foo matches both ‘foo’ and ‘foobar’, while the regular expression foo$ matches only ‘foo’. More interestingly, searching for foo.$ in 'foo1\nfoo2\n' matches ‘foo2’ normally, but ‘foo1’ in MULTILINE mode; searching for a single $ in 'foo\n' will find two [empty] matches: one just before the newline, and one at the end of the string.'*'Causes the resulting RE to match 0 or more repetitions of the preceding RE, as many repetitions as are possible. ab* will match ‘a’, ‘ab’, or ‘a’ followed by any number of ‘b’s.'+'Causes the resulting RE to match 1 or more repetitions of the preceding RE. ab+ will match ‘a’ followed by any non-zero number of ‘b’s; it will not match just ‘a’.'?'Causes the resulting RE to match 0 or 1 repetitions of the preceding RE. ab? will match either ‘a’ or ‘ab’.*?, +?, ??The '*', '+', and '?' qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn’t desired; if the RE is matched against '

title

'
, it will match the entire string, and not just '

'. Adding '?' after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using .*? in the previous expression will match only '

'.{m}Specifies that exactly m copies of the previous RE should be matched; fewer matches cause the entire RE not to match. For example, a{6} will match exactly six 'a' characters, but not five.{m,n}Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as many repetitions as possible. For example, a{3,5} will match from 3 to 5 'a' characters. Omitting m specifies a lower bound of zero, and omitting n specifies an infinite upper bound. As an example, a{4,}b will match aaaab or a thousand 'a' characters followed by a b, but not aaab. The comma may not be omitted or the modifier would be confused with the previously described form.{m,n}?Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as few repetitions as possible. This is the non-greedy version of the previous qualifier. For example, on the 6-character string 'aaaaaa', a{3,5} will match 5 'a' characters, while a{3,5}? will only match 3 characters.'\'

Hoặc thoát khỏi các ký tự đặc biệt [cho phép bạn khớp các ký tự như '*', '?', V.v.], hoặc báo hiệu một chuỗi đặc biệt; Trình tự đặc biệt được thảo luận dưới đây.'*', '?', and so forth], or signals a special sequence; special sequences are discussed below.

Nếu bạn không sử dụng một chuỗi thô để diễn đạt mẫu, hãy nhớ rằng Python cũng sử dụng dấu gạch chéo ngược như một chuỗi thoát trong các chữ viết; Nếu trình tự thoát được công nhận bởi trình phân tích cú pháp Python, thì dấu gạch chéo ngược và ký tự tiếp theo được bao gồm trong chuỗi kết quả. Tuy nhiên, nếu Python sẽ nhận ra chuỗi kết quả, dấu gạch chéo ngược nên được lặp lại hai lần. Điều này rất phức tạp và khó hiểu, vì vậy, nó rất khuyến khích bạn sử dụng các chuỗi thô cho tất cả nhưng các biểu thức đơn giản nhất.

[]

Được sử dụng để chỉ ra một tập hợp các ký tự. Trong một tập hợp:

  • Các ký tự có thể được liệt kê riêng lẻ, ví dụ: [AMK] sẽ khớp với 'A', 'M' hoặc 'K'.[amk] will match 'a', 'm', or 'k'.
  • Các phạm vi ký tự có thể được biểu thị bằng cách đưa hai ký tự và tách chúng bằng '-', ví dụ [A-Z] sẽ khớp với bất kỳ chữ cái viết thường nào, [0-5] [0-9] sẽ khớp với tất cả các số hai chữ số từ 00 đến 59 và [0-9a-fa-f] sẽ phù hợp với bất kỳ chữ số thập lục phân nào. Nếu-được thoát ra [ví dụ: [a \ -z]] hoặc nếu nó được đặt là ký tự đầu tiên hoặc cuối cùng [ví dụ: [a-]], nó sẽ khớp với một chữ '-'.'-', for example [a-z] will match any lowercase ASCII letter, [0-5][0-9] will match all the two-digits numbers from 00 to 59, and [0-9A-Fa-f] will match any hexadecimal digit. If - is escaped [e.g. [a\-z]] or if it’s placed as the first or last character [e.g. [a-]], it will match a literal '-'.
  • Các nhân vật đặc biệt mất ý nghĩa đặc biệt của họ bên trong bộ. Ví dụ: [[+*]] sẽ khớp với bất kỳ ký tự nghĩa đen nào '[', '+', '*' hoặc ']'.[[+*]] will match any of the literal characters '[', '+', '*', or ']'.
  • Các lớp ký tự như \ w hoặc \ s [được xác định bên dưới] cũng được chấp nhận bên trong một tập hợp, mặc dù các ký tự mà chúng phù hợp phụ thuộc vào việc ASCII hay chế độ Locale có hiệu lực hay không.\w or \S [defined below] are also accepted inside a set, although the characters they match depends on whether ASCII or LOCALE mode is in force.
  • Các ký tự không nằm trong phạm vi có thể được khớp bằng cách bổ sung cho tập hợp. Nếu ký tự đầu tiên của tập hợp là '^', tất cả các ký tự không có trong tập hợp sẽ được khớp. Ví dụ: [^5] sẽ phù hợp với bất kỳ ký tự nào ngoại trừ '5' và [^^] sẽ phù hợp với bất kỳ ký tự nào ngoại trừ '^'. ^ không có ý nghĩa đặc biệt nếu nó không phải là nhân vật đầu tiên trong tập hợp.'^', all the characters that are not in the set will be matched. For example, [^5] will match any character except '5', and [^^] will match any character except '^'. ^ has no special meaning if it’s not the first character in the set.
  • Để phù hợp với một chữ ']' bên trong một bộ, đi trước nó với một dấu gạch chéo ngược hoặc đặt nó vào đầu bộ. Ví dụ: cả [[] [\] {}] và [] [] [{}] sẽ cả hai khớp với dấu ngoặc đơn.']' inside a set, precede it with a backslash, or place it at the beginning of the set. For example, both [[][\]{}] and [][][{}] will both match a parenthesis.
'. theo cách này. Điều này có thể được sử dụng bên trong các nhóm [xem bên dưới] là tốt. Khi chuỗi đích được quét, res được phân tách bởi '|' được thử từ trái sang phải. Khi một mẫu hoàn toàn phù hợp, nhánh đó được chấp nhận. Điều này có nghĩa là một khi A khớp, B sẽ không được kiểm tra thêm, ngay cả khi nó sẽ tạo ra một trận đấu tổng thể dài hơn. Nói cách khác, '|' Nhà điều hành không bao giờ tham lam. Để phù hợp với chữ '|', sử dụng \ | hoặc đặt nó bên trong một lớp ký tự, như trong [|]. [...] khớp với bất kỳ biểu thức chính quy nào nằm trong dấu ngoặc đơn và chỉ ra sự khởi đầu và kết thúc của một nhóm; Nội dung của một nhóm có thể được truy xuất sau khi một trận đấu được thực hiện và có thể được khớp sau trong chuỗi với chuỗi đặc biệt \ Number, được mô tả bên dưới. Để phù hợp với các chữ '[' hoặc ']', sử dụng \ [hoặc \] hoặc đặt chúng bên trong một lớp ký tự: [[] []]. [? ...] Đây là một ký hiệu mở rộng [A '?' Theo sau '[' không có ý nghĩa khác]. Nhân vật đầu tiên sau '?' Xác định ý nghĩa và cú pháp tiếp theo của cấu trúc là gì. Các phần mở rộng thường không tạo ra một nhóm mới; [? P ...] Ngoại lệ cho quy tắc này. Sau đây là các tiện ích mở rộng hiện được hỗ trợ. [? AILMSUX]A|B, where A and B can be arbitrary REs, creates a regular expression that will match either A or B. An arbitrary number of REs can be separated by the '|' in this way. This can be used inside groups [see below] as well. As the target string is scanned, REs separated by '|' are tried from left to right. When one pattern completely matches, that branch is accepted. This means that once A matches, B will not be tested further, even if it would produce a longer overall match. In other words, the '|' operator is never greedy. To match a literal '|', use \|, or enclose it inside a character class, as in [|].[...]Matches whatever regular expression is inside the parentheses, and indicates the start and end of a group; the contents of a group can be retrieved after a match has been performed, and can be matched later in the string with the \number special sequence, described below. To match the literals '[' or ']', use \[ or \], or enclose them inside a character class: [[] []].[?...] This is an extension notation [a '?' following a '[' is not meaningful otherwise]. The first character after the '?' determines what the meaning and further syntax of the construct is. Extensions usually do not create a new group; [?P...] is the only exception to this rule. Following are the currently supported extensions.[?aiLmsux]

. Các chữ cái đặt các cờ tương ứng: re.a [khớp ASCII-chỉ], re.i [trường hợp bỏ qua], re.l [phụ thuộc locale], re.m [multi-line], re.s [dot khớp với tất cả và re.x [verbose], cho toàn bộ biểu thức chính quy. .'a', 'i', 'L', 'm', 's', 'u', 'x'.] The group matches the empty string; the letters set the corresponding flags: re.A [ASCII-only matching], re.I [ignore case], re.L [locale dependent], re.M [multi-line], re.S [dot matches all], and re.X [verbose], for the entire regular expression. [The flags are described in Module Contents.] This is useful if you wish to include the flags as part of the regular expression, instead of passing a flag argument to the re.compile[] function.

Lưu ý rằng cờ [? X] thay đổi cách biểu thức được phân tích cú pháp. Nó nên được sử dụng đầu tiên trong chuỗi biểu thức hoặc sau một hoặc nhiều ký tự khoảng trắng. Nếu có các ký tự không phải là màu trước khi cờ, kết quả không được xác định.[?x] flag changes how the expression is parsed. It should be used first in the expression string, or after one or more whitespace characters. If there are non-whitespace characters before the flag, the results are undefined.

[?: ...] Một phiên bản không bắt giữ của dấu ngoặc đơn thông thường. Khớp với bất kỳ biểu thức chính quy nào nằm trong dấu ngoặc đơn, nhưng không thể lấy được chuỗi con phù hợp sau khi thực hiện một trận đấu hoặc được tham chiếu sau trong mẫu. [? P ...]A non-capturing version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern.[?P...]

Tương tự như dấu ngoặc đơn thông thường, nhưng phần phụ được khớp với tên nhóm có thể truy cập thông qua tên nhóm tượng trưng. Tên nhóm phải là định danh Python hợp lệ và mỗi tên nhóm chỉ được xác định một lần trong một biểu thức chính quy. Một nhóm tượng trưng cũng là một nhóm được đánh số, giống như nhóm không được đặt tên.

Named groups can be referenced in three contexts. If the pattern is [?P['"]].*?[?P=quote] [i.e. matching a string quoted with either single or double quotes]:

Context of reference to group “quote”Ways to reference it
in the same pattern itself
  • [?P=quote] [as shown]
  • \1
when processing match object m
  • m.group['quote']
  • m.end['quote'] [etc.]
in a string passed to the repl argument of re.sub[]
  • \g
  • \g
  • \1
[?P=name]A backreference to a named group; it matches whatever text was matched by the earlier group named name.[?#...]A comment; the contents of the parentheses are simply ignored.[?=...]Matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead assertion. For example, Isaac [?=Asimov] will match 'Isaac ' only if it’s followed by 'Asimov'.[?!...]Matches if ... doesn’t match next. This is a negative lookahead assertion. For example, Isaac [?!Asimov] will match 'Isaac ' only if it’s not followed by 'Asimov'. [?> import re >>> m = re.search['[?' as well as '', but not with ''.

The special sequences consist of '\' and a character from the list below. If the ordinary character is not on the list, then the resulting RE will match the second character. For example, \$ matches the character '$'.

\numberMatches the contents of the group of the same number. Groups are numbered starting from 1. For example, [.+] \1 matches 'the the' or '55 55', but not 'thethe' [note the space after the group]. This special sequence can only be used to match one of the first 99 groups. If the first digit of number is 0, or number is 3 octal digits long, it will not be interpreted as a group match, but as the character with octal value number. Inside the '[' and ']' of a character class, all numeric escapes are treated as characters.\AMatches only at the start of the string.\b

Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of Unicode alphanumeric or underscore characters, so the end of a word is indicated by whitespace or a non-alphanumeric, non-underscore Unicode character. Note that formally, \b is defined as the boundary between a \w and a \W character [or vice versa], or between \w and the beginning/end of the string. This means that r'\bfoo\b' matches 'foo', 'foo.', '[foo]', 'bar foo baz' but not 'foobar' or 'foo3'.

By default Unicode alphanumerics are the ones used, but this can be changed by using the ASCII flag. Inside a character range, \b represents the backspace character, for compatibility with Python’s string literals.

\BMatches the empty string, but only when it is not at the beginning or end of a word. This means that r'py\B' matches 'python', 'py3', 'py2', but not 'py', 'py.', or 'py!'. \B is just the opposite of \b, so word characters are Unicode alphanumerics or the underscore, although this can be changed by using the ASCII flag.\d For Unicode [str] patterns:Matches any Unicode decimal digit [that is, any character in Unicode character category [Nd]]. This includes [0-9], and also many other digit characters. If the ASCII flag is used only [0-9] is matched [but the flag affects the entire regular expression, so in such cases using an explicit [0-9] may be a better choice].For 8-bit [bytes] patterns:Matches any decimal digit; this is equivalent to [0-9].\DMatches any character which is not a Unicode decimal digit. This is the opposite of \d. If the ASCII flag is used this becomes the equivalent of [^0-9] [but the flag affects the entire regular expression, so in such cases using an explicit [^0-9] may be a better choice].\sFor Unicode [str] patterns:Matches Unicode whitespace characters [which includes [ \t\n\r\f\v], and also many other characters, for example the non-breaking spaces mandated by typography rules in many languages]. If the ASCII flag is used, only [ \t\n\r\f\v] is matched [but the flag affects the entire regular expression, so in such cases using an explicit [ \t\n\r\f\v] may be a better choice].For 8-bit [bytes] patterns:Matches characters considered whitespace in the ASCII character set; this is equivalent to [ \t\n\r\f\v].\SMatches any character which is not a Unicode whitespace character. This is the opposite of \s. If the ASCII flag is used this becomes the equivalent of [^ \t\n\r\f\v] [but the flag affects the entire regular expression, so in such cases using an explicit [^ \t\n\r\f\v] may be a better choice].\wFor Unicode [str] patterns:Matches Unicode word characters; this includes most characters that can be part of a word in any language, as well as numbers and the underscore. If the ASCII flag is used, only [a-zA-Z0-9_] is matched [but the flag affects the entire regular expression, so in such cases using an explicit [a-zA-Z0-9_] may be a better choice].For 8-bit [bytes] patterns:Matches characters considered alphanumeric in the ASCII character set; this is equivalent to [a-zA-Z0-9_].\WMatches any character which is not a Unicode word character. This is the opposite of \w. If the ASCII flag is used this becomes the equivalent of [^a-zA-Z0-9_] [but the flag affects the entire regular expression, so in such cases using an explicit [^a-zA-Z0-9_] may be a better choice].\ZMatches only at the end of the string.

Hầu hết các ESCAPES tiêu chuẩn được hỗ trợ bởi các chuỗi chuỗi Python cũng được chấp nhận bởi trình phân tích cú pháp biểu thức thông thường:

\a      \b      \f      \n
\r      \t      \u      \U
\v      \x      \\

.\b is used to represent word boundaries, and means “backspace” only inside character classes.]

Các chuỗi thoát '\ u' và '\ u' chỉ được nhận ra trong các mẫu Unicode. Trong các mẫu byte, chúng không được đối xử đặc biệt. and '\U' escape sequences are only recognized in Unicode patterns. In bytes patterns they are not treated specially.

Escapes octal được bao gồm trong một hình thức giới hạn. Nếu chữ số đầu tiên là 0, hoặc nếu có ba chữ số bát phân, thì nó được coi là một lối thoát bát phân. Nếu không, nó là một tham chiếu nhóm. Đối với các chuỗi chữ, thoát hiểm luôn luôn có chiều dài tối đa ba chữ số.

Đã thay đổi trong phiên bản 3.3: Các chuỗi thoát '\ u' và '\ u' đã được thêm vào.The '\u' and '\U' escape sequences have been added.

6.2.2. Nội dung mô -đun

Mô -đun xác định một số chức năng, hằng số và một ngoại lệ. Một số chức năng là phiên bản đơn giản hóa của các phương thức nổi bật đầy đủ cho các biểu thức thông thường được biên dịch. Hầu hết các ứng dụng không tầm thường luôn sử dụng biểu mẫu được biên dịch.

re.compile [mẫu, cờ = 0] ¶

Biên dịch một mẫu biểu thức chính quy thành một đối tượng biểu thức chính quy, có thể được sử dụng để khớp bằng các phương thức khớp [] và tìm kiếm [], được mô tả bên dưới.match[] and search[] methods, described below.

Hành vi biểu thức có thể được sửa đổi bằng cách chỉ định giá trị cờ. Các giá trị có thể là bất kỳ biến nào sau đây, kết hợp bằng bitwise hoặc [| toán tử].| operator].

Trình tự

prog = re.compile[pattern]
result = prog.match[string]

tương đương với

result = re.match[pattern, string]

Nhưng sử dụng re.compile [] và lưu đối tượng biểu thức chính quy kết quả để sử dụng lại hiệu quả hơn khi biểu thức sẽ được sử dụng nhiều lần trong một chương trình.re.compile[] and saving the resulting regular expression object for reuse is more efficient when the expression will be used several times in a single program.

Ghi chú

Các phiên bản được biên dịch của các mẫu gần đây nhất được truyền cho re.match [], re.search [] hoặc re.compile [] được lưu trong bộ nhớ cach .re.match[], re.search[] or re.compile[] are cached, so programs that use only a few regular expressions at a time needn’t worry about compiling regular expressions.

Re.a¶ Re.ascii¶

Tạo \ w, \ w, \ b, \ b, \ d, \ d, \ s và \ s phù hợp với ASCII-chỉ thay vì khớp unicode đầy đủ. Điều này chỉ có ý nghĩa đối với các mẫu Unicode và bị bỏ qua cho các mẫu byte.\w, \W, \b, \B, \d, \D, \s and \S perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode patterns, and is ignored for byte patterns.

Lưu ý rằng để tương thích ngược, cờ RE.U vẫn tồn tại [cũng như từ đồng nghĩa của nó re.unicode và đối tác nhúng của nó [? Kết hợp không được phép cho byte].re.U flag still exists [as well as its synonym re.UNICODE and its embedded counterpart [?u]], but these are redundant in Python 3 since matches are Unicode by default for strings [and Unicode matching isn’t allowed for bytes].

Re.debug¶

Hiển thị thông tin gỡ lỗi về biểu thức biên dịch.

Re.I¶ re.ignorecase¶

Thực hiện kết hợp không nhạy cảm trường hợp; Biểu thức như [A-Z] cũng sẽ khớp với các chữ cái viết thường. Điều này không bị ảnh hưởng bởi địa phương hiện tại và hoạt động cho các ký tự Unicode như mong đợi.[A-Z] will match lowercase letters, too. This is not affected by the current locale and works for Unicode characters as expected.

Re.l¶ Re.Locale¶

Tạo \ w, \ w, \ b, \ b, \ s và \ s phụ thuộc vào địa phương hiện tại. Việc sử dụng lá cờ này không được khuyến khích vì cơ chế địa phương rất không đáng tin cậy và dù sao nó cũng chỉ xử lý một nền văn hóa của người Hồi giáo tại một thời điểm; Thay vào đó, bạn nên sử dụng Unicode khớp, đây là mặc định trong Python 3 cho các mẫu Unicode [STR].\w, \W, \b, \B, \s and \S dependent on the current locale. The use of this flag is discouraged as the locale mechanism is very unreliable, and it only handles one “culture” at a time anyway; you should use Unicode matching instead, which is the default in Python 3 for Unicode [str] patterns.

Re.m¶ Re.Multiline¶

Khi được chỉ định, ký tự mẫu '^' khớp ở đầu chuỗi và ở đầu mỗi dòng [ngay sau mỗi dòng mới]; và ký tự mẫu '$' khớp ở cuối chuỗi và ở cuối mỗi dòng [ngay trước mỗi dòng mới]. Theo mặc định, '^' chỉ khớp với đầu chuỗi và '$' chỉ ở cuối chuỗi và ngay trước dòng mới [nếu có] ở cuối chuỗi.'^' matches at the beginning of the string and at the beginning of each line [immediately following each newline]; and the pattern character '$' matches at the end of the string and at the end of each line [immediately preceding each newline]. By default, '^' matches only at the beginning of the string, and '$' only at the end of the string and immediately before the newline [if any] at the end of the string.

Re.s¶ Re.Dotall¶

Làm cái '.' Nhân vật đặc biệt phù hợp với bất kỳ nhân vật nào, bao gồm một dòng mới; không có lá cờ này, '.' sẽ phù hợp với bất cứ điều gì ngoại trừ một dòng mới.'.' special character match any character at all, including a newline; without this flag, '.' will match anything except a newline.

Re.x¶ Re.verbose¶

Cờ này cho phép bạn viết các biểu thức thông thường trông đẹp hơn. Khoảng trắng trong mẫu bị bỏ qua, ngoại trừ khi trong một lớp ký tự hoặc đi trước bởi một dấu gạch chéo ngược không được xác định và, khi một dòng chứa '#' không trong một lớp ký tự hoặc trước một dấu gạch chéo ngược không có 'Qua cuối dòng bị bỏ qua.'#' neither in a character class or preceded by an unescaped backslash, all characters from the leftmost such '#' through the end of the line are ignored.

Điều đó có nghĩa là hai đối tượng biểu thức chính quy sau phù hợp với số thập phân có chức năng bằng nhau:

a = re.compile[r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X]
b = re.compile[r"\d+\.\d*"]

Re.Search [mẫu, chuỗi, cờ = 0] ¶

Quét qua chuỗi Tìm kiếm một vị trí nơi mẫu biểu thức chính quy tạo ra một khớp và trả về một đối tượng khớp tương ứng. Trả về không nếu không có vị trí trong chuỗi khớp với mẫu; Lưu ý rằng điều này khác với việc tìm một trận đấu có độ dài bằng không tại một số điểm trong chuỗi.None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

Re.match [mẫu, chuỗi, cờ = 0] ¶

Nếu số không hoặc nhiều ký tự ở đầu chuỗi khớp với mẫu biểu thức chính quy, hãy trả về một đối tượng khớp tương ứng. Trả về không nếu chuỗi không khớp với mẫu; Lưu ý rằng điều này khác với một trận đấu có độ dài bằng không.None if the string does not match the pattern; note that this is different from a zero-length match.

Lưu ý rằng ngay cả trong chế độ đa dòng, re.match [] sẽ chỉ khớp ở đầu chuỗi và không ở đầu mỗi dòng.MULTILINE mode, re.match[] will only match at the beginning of the string and not at the beginning of each line.

Nếu bạn muốn xác định vị trí đối sánh ở bất cứ đâu trong chuỗi, hãy sử dụng search [] thay vào đó [xem thêm search [] so với match []].search[] instead [see also search[] vs. match[]].

Re.Split [mẫu, chuỗi, maxsplit = 0, cờ = 0] ¶

Chuỗi phân chia theo các lần xuất hiện của mẫu. Nếu chụp dấu ngoặc đơn được sử dụng trong mẫu, thì văn bản của tất cả các nhóm trong mẫu cũng được trả về như một phần của danh sách kết quả. Nếu MAXSplit là không khác biệt, tại hầu hết các phân tách MaxSplit xảy ra và phần còn lại của chuỗi được trả về làm yếu tố cuối cùng của danh sách.

>>> 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]
['0', '3', '9']

Nếu có các nhóm bắt giữ trong dấu phân cách và nó khớp với đầu chuỗi, kết quả sẽ bắt đầu bằng một chuỗi trống. Tương tự giữ cho phần cuối của chuỗi:

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

Bằng cách đó, các thành phần phân tách luôn được tìm thấy tại cùng một chỉ số tương đối trong danh sách kết quả.

Lưu ý rằng Split sẽ không bao giờ chia một chuỗi trên một kết hợp mẫu trống. Ví dụ:

>>> re.split['x*', 'foo']
['foo']
>>> re.split["[?m]^$", "foo\n\nbar\n"]
['foo\n\nbar\n']

Đã thay đổi trong phiên bản 3.1: Đã thêm đối số cờ tùy chọn.Added the optional flags argument.

re.findall [mẫu, chuỗi, cờ = 0] ¶

Trả về tất cả các trận đấu không chồng chéo của mẫu trong chuỗi, như một danh sách các chuỗi. Chuỗi được quét từ trái sang phải và các trận đấu được trả về theo thứ tự được tìm thấy. Nếu một hoặc nhiều nhóm có mặt trong mẫu, hãy trả lại danh sách các nhóm; Đây sẽ là một danh sách các bộ dữ liệu nếu mẫu có nhiều hơn một nhóm. Các trận đấu trống được bao gồm trong kết quả trừ khi họ chạm vào sự khởi đầu của một trận đấu khác.

re.finditer [mẫu, chuỗi, cờ = 0] ¶

Trả về một iterator mang lại các đối tượng khớp trên tất cả các kết quả không chồng chéo cho mẫu RE trong chuỗi. Chuỗi được quét từ trái sang phải và các trận đấu được trả về theo thứ tự được tìm thấy. Các trận đấu trống được bao gồm trong kết quả trừ khi họ chạm vào sự khởi đầu của một trận đấu khác.

Re.sub [mẫu, repl, chuỗi, đếm = 0, cờ = 0] ¶

Trả về chuỗi thu được bằng cách thay thế các lần xuất hiện không chồng chéo bên trái của mẫu trong chuỗi bằng cách thay thế. Nếu mẫu được tìm thấy, chuỗi được trả về không thay đổi. REPREP có thể là một chuỗi hoặc một hàm; Nếu đó là một chuỗi, bất kỳ dấu gạch chéo ngược nào thoát trong đó được xử lý. Nghĩa là, \ n được chuyển đổi thành một ký tự dòng mới, \ r được chuyển đổi thành trở lại vận chuyển, v.v. Những lối thoát chưa biết như \ J bị bỏ lại một mình. Các bản sao lưu, chẳng hạn như \ 6, được thay thế bằng chuỗi con phù hợp với nhóm 6 trong mẫu. Ví dụ:\n is converted to a single newline character, \r is converted to a carriage return, and so forth. Unknown escapes such as \j are left alone. Backreferences, such as \6, are replaced with the substring matched by group 6 in the pattern. For example:

>>> re.sub[r'def\s+[[a-zA-Z_][a-zA-Z_0-9]*]\s*\[\s*\]:',
...        r'static PyObject*\npy_\1[void]\n{',
...        'def myfunc[]:']
'static PyObject*\npy_myfunc[void]\n{'

Nếu thay thế là một hàm, nó được gọi cho mọi lần xuất hiện không chồng chéo của mẫu. Hàm có một đối số đối tượng khớp và trả về chuỗi thay thế. Ví dụ:

>>> m = re.search['[?

Bài Viết Liên Quan

Chủ Đề