Python Regular Expressions

Regular Expressions

regular expression มีไว้สำหรับ ช่วยให้เราค้นหาข้อความตาม pattern

ใน python จะต้องโหลดโมดูล re เพื่อใช้งานความสามารถทางด้าน regular expression ของ python ซึ่งโมดูลนี้ความสามารถเหมือนกับ ของ ภาษา Perl ฟังก์ชั่น ในการค้นหา ข้อความตามรูปแบบที่ต้องการ

The match Function  
re.match(pattern, string, flags=0)  
re.search(pattern, string, flags=0)

pattern สำหรับใช้ค้นหาข้อความตามรูปแบบใน python ต้องขึ้นด้วย r'expression' pattern คือ รูปแบบต้องที่เรากำหนดเพื่อหาความเหมือนในข้อความ string คือข้อความที่ต้องการค้นหา flags คือรูปแบบในการค้นหาดูได้ตามตาราง

ทั้งสองฟังก์ชั่นจะคือค่า object ที่เหมือนออกมา และ None ถ้าไม่เจอ เราสามารถใช้ group(num) or groups()

Regular-expression Modifiers - Option Flags

กำหนดรูปแบบในการค้นหา ถ้าต้องการใช้มากกว่า 1 กฏของการค้นหา เราสามารถใช้ or (|)

Modifier

Description

re.I

สนใจตัวพิมพ์เล็กพิมพ์ใหญ่

re.L

Interprets words according to the current locale. This interpretation affects the alphabetic group (\w and \W), as well as word boundary behavior (\b and \B).

re.M

กำหนด $ ตรงตามจบบันทัด กำหนด ^ ขึ้นต้นด้วยบันทัด

re.S

ใช้เครื่องหมาย . (dot) ตรงตามตัวอักษรใดๆ รวมถึงขึ้นบรรทัดใหม่ด้วย Makes a period (dot) match any character, including a newline.

re.U

ตรงตามข้อความ unicode Interprets letters according to the Unicode character set. This flag affects the behavior of \w, \W, \b, \B.

re.X

ไม่สนใจ ช่องว่าง

Regular-expression patterns:

Except for control characters, (+ ? . * ^ $ ( ) [ ] { } | ), all characters match themselves. You can escape a control character by preceding it with a backslash.

ตางรางรุปบบ regular expression ที่สามารถใช้เป็นเงื่อนไขในการค้นหาได้ ใน python

Pattern

Description

^

ตรง เริ่มต้นบรรทัด

$

ตรง สุดท้ายของบรรทัด

.

ตรงตัวอักษรใดๆ ยกเว้นการขึ้นบรรทัดใหม่ ถ้าให้ตรงตามขึ้นบรรทัดใหม่ด้วย ให้ใช้ option m

[...]

ตรงตัวอักษรใดๆ ในเครื่องหมาย []

Matches any single character not in brackets

re*

Matches 0 or more occurrences of preceding expression.

re+

Matches 1 or more occurrence of preceding expression.

re?

Matches 0 or 1 occurrence of preceding expression.

re{ n}

Matches exactly n number of occurrences of preceding expression.

re{ n,}

Matches n or more occurrences of preceding expression.

re{ n, m}

Matches at least n and at most m occurrences of preceding expression.

a

b

Matches either a or b.

(re)

Groups regular expressions and remembers matched text.

(?imx)

Temporarily toggles on i, m, or x options within a regular expression. If in parentheses, only that area is affected.

(?-imx)

Temporarily toggles off i, m, or x options within a regular expression. If in parentheses, only that area is affected.

(?: re)

Groups regular expressions without remembering matched text.

(?imx: re)

Temporarily toggles on i, m, or x options within parentheses.

(?-imx: re)

Temporarily toggles off i, m, or x options within parentheses.

(?#...)

Comment.

(?= re)

Specifies position using a pattern. Doesn't have a range.

(?! re)

Specifies position using pattern negation. Doesn't have a range.

(?> re)

Matches independent pattern without backtracking.

\w

Matches word characters.

\W

Matches nonword characters.

\s

Matches whitespace. Equivalent to [\t\n\r\f].

\S

Matches nonwhitespace.

\d

Matches digits. Equivalent to [0-9].

\D

Matches nondigits.

\A

Matches beginning of string.

\Z

Matches end of string. If a newline exists, it matches just before newline.

\z

Matches end of string.

\G

Matches point where last match finished.

\b

Matches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets.

\B

Matches nonword boundaries.

\n, \t, etc.

Matches newlines, carriage returns, tabs, etc.

\1...\9

Matches nth grouped subexpression.

\10

Matches nth grouped subexpression if it matched already. Otherwise refers to the octal representation of a character code.

Regular-expression Examples

Literal characters:

Example

Description

Match

"python".

Character classes:

Example

Description

[Pp]ython

Match "Python" or "python"

rub[ye]

Match "ruby" or "rube"

[aeiou]

Match any one lowercase vowel

[0-9]

Match any digit; same as [0123456789]

[a-z]

Match any lowercase ASCII letter

[A-Z]

Match any uppercase ASCII letter

[a-zA-Z0-9]

Match any of the above

Match anything other than a lowercase vowel

Match anything other than a digit

Special Character Classes:

Example

Description

.

Match any character except newline

\d

Match a digit: [0-9]

\D

Match a nondigit:

\s

Match a whitespace character: [ \t\r\n\f]

\S

Match nonwhitespace:

\w

Match a single word character: [A-Za-z0-9_]

\W

Match a nonword character:

Repetition Cases:

Example

Description

ruby?

Match "rub" or "ruby": the y is optional

ruby*

Match "rub" plus 0 or more ys

ruby+

Match "rub" plus 1 or more ys

\d{3}

Match exactly 3 digits

\d{3,}

Match 3 or more digits

\d{3,5}

Match 3, 4, or 5 digits

Nongreedy repetition: This matches the smallest number of repetitions:

Example

Description

<.*>

Greedy repetition: matches "perl>"

<.*?>

Nongreedy: matches "" in "perl>"

Grouping with parentheses:

Example

Description

\D\d+

No group: + repeats \d

(\D\d)+

Grouped: + repeats \D\d pair

([Pp]ython(, )?)+

Match "Python", "Python, python, python", etc.

Backreferences: This matches a previously matched group again:

Example

Description

([Pp])ython&\1ails

Match python&pails or Python&Pails

(['"])*\1

Single or double-quoted string. \1 matches whatever the 1st group matched . \2 matches whatever the 2nd group matched, etc.

Alternatives:

Example

Description

python|perl

Match “python” or “perl”

rub(y|le))

Match “ruby” or “ruble”

Python(!+|\?)

Python followed by one or more ! or one ?

Anchors: This needs to specify match position.

Example

Description

^Python

Match "Python" at the start of a string or internal line

Python$

Match "Python" at the end of a string or line

\APython

Match "Python" at the start of a string

Python\Z

Match "Python" at the end of a string

\bPython\b

Match "Python" at a word boundary

\brub\B

\B is nonword boundary: match "rub" in "rube" and "ruby" but not alone

Python(?=!)

Match "Python", if followed by an exclamation point

Python(?!!)

Match "Python", if not followed by an exclamation point

Special syntax with parentheses:

Example

Description

R(?#comment)

Matches "R". All the rest is a comment

R(?i)uby

Case-insensitive while matching "uby"

R(?i:uby)

Same as above

rub(?:y|le)

Group only without creating \1 backreference

บทความเพิ่มเติม :

Reference : mindphp.com/บทเรียนออนไลน์/83-python/2923-python-regular-expressions.html

Last updated