貪婪與非貪婪比對

Python 中的正規表示法

Maria Eugenia Inzaugarat

Data Scientist

貪婪與非貪婪比對

  • 兩種比對方式:

    • 貪婪(Greedy)
    • 非貪婪(Lazy)
  • 標準量詞預設為貪婪:*+?{num, num}

Python 中的正規表示法

貪婪比對

  • 「貪婪」:盡可能多配對字元

  • 回傳最長的比對

import re
re.match(r"\d+", "12345bcada")
<re.Match object; span=(0, 5), match='12345'>

Python 中的正規表示法

貪婪比對

  • 若配對過多會回溯

  • 一次放棄一個字元

import re
re.match(r".*hello", "xhelloxxxxxx")
<re.Match object; span=(0, 6), match='xhello'>

Python 中的正規表示法

非貪婪比對

  • 「非貪婪」:只配對所需最少字元
  • 回傳最短的比對
  • 在貪婪量詞後加上 ?
import re
re.match(r"\d+?", "12345bcada")
<re.Match object; span=(0, 1), match='1'>

Python 中的正規表示法

非貪婪比對

  • 若配對過少會回溯

  • 一次擴張一個字元

import re
re.match(r".*?hello", "xhelloxxxxxx")
<re.Match object; span=(0, 6), match='xhello'>

Python 中的正規表示法

一起來練習吧!

Python 中的正規表示法

Preparing Video For Download...