正規表示式簡介

Python 中的正規表示法

Maria Eugenia Inzaugarat

Data Scientist

什麼是正規表示式?

REGular EXpression,簡稱 regex:

由一般字元與特殊中繼字元組成的字串,用來描述在文字中尋找文字或位置的樣式

Python 中的正規表示法

什麼是正規表示式?

REGular EXpression,簡稱 regex:

String containing a combination of normal characters and special metacharacters that describes patterns to find text or positions within a text

  • 一般字元會匹配自身(st
Python 中的正規表示法

什麼是正規表示式?

REGular EXpression,簡稱 regex:

String containing a combination of normal characters and special metacharacters that describes patterns to find text or positions within a text

  • 中繼字元表示字元類型(\d\s\w)或概念({3,10}
Python 中的正規表示法

什麼是正規表示式?

REGular EXpression,簡稱 regex:

String containing a combination of normal characters and special metacharacters that describes patterns to find text or positions within a text

  • 中繼字元表示字元類型(\d\s\w)或概念({3,10}
Python 中的正規表示法

什麼是正規表示式?

REGular EXpression,簡稱 regex:

String containing a combination of normal characters and special metacharacters that describes patterns to find text or positions within a text

  • 中繼字元表示字元類型(\d\s\w)或概念({3,10}
Python 中的正規表示法

什麼是正規表示式?

REGular EXpression,簡稱 regex:

String containing a combination of normal characters and special metacharacters that describes patterns to find text or positions within a text

  • 中繼字元表示字元類型(\d\s\w)或概念({3,10}
Python 中的正規表示法

什麼是正規表示式?

REGular EXpression,簡稱 regex:

String containing a combination of normal characters and special metacharacters that describes patterns to find text or positions within a text

  • 樣式:對應到文字或標點的一連串字元
Python 中的正規表示法

什麼是正規表示式?

REGular EXpression,簡稱 regex:

String containing a combination of normal characters and special metacharacters that describes patterns to find text or positions within a text

  • 樣式比對用途:

    • 尋找並取代文字
    • 驗證字串
  • 非常強大且快速

Python 中的正規表示法

re 模組

import re
  • 尋找樣式的所有相符項:

re.findall(r"#movies", "Love #movies! I had fun yesterday going to the #movies")
['#movies', '#movies']
Python 中的正規表示法

re 模組

import re
  • 依每個相符處切割字串:

re.split(r"!", "Nice Place to eat! I'll come back! Excellent meat!")
['Nice Place to eat', " I'll come back", ' Excellent meat', '']
Python 中的正規表示法

re 模組

import re
  • 以字串取代一個或多個相符項:

re.sub(r"yellow", "nice", "I have a yellow car and a yellow house in a yellow neighborhood")
'I have a nice car and a nice house in a nice neighborhood'
Python 中的正規表示法

支援的中繼字元

re.findall(r"User\d", "The winners are: User9, UserN, User8")
['User9', 'User8']

re.findall(r"User\D", "The winners are: User9, UserN, User8")
['UserN']
Python 中的正規表示法

支援的中繼字元

re.findall(r"User\w", "The winners are: User9, UserN, User8")
['User9', 'UserN', 'User8']

re.findall(r"\W\d", "This skirt is on sale, only $5 today!")
['$5']
Python 中的正規表示法

支援的中繼字元

re.findall(r"Data\sScience", "I enjoy learning Data Science")
['Data Science']

re.sub(r"ice\Scream", "ice cream", "I really like ice-cream")
'I really like ice cream'
Python 中的正規表示法

一起來練習吧!

Python 中的正規表示法

Preparing Video For Download...