python正則表達式入門一

正則表達式入門導包

import re

常用示例

  • 以某個字符串開頭
^
  • 任意字符
	.

就是一個英文的句號

  • 任意多次
*

示例

line = "tpr123"
regex_str = "^t.*"
if re.match(regex_str, line):
    print("匹配成功")

結果

D:\pythonworkspace\regexp\venv\Scripts\python.exe D:/pythonworkspace/regexp/test/test.py
匹配成功

  • 以某個值爲結尾
$

示例

line = "tpr123"
regex_str = "^t.*3$"
if re.match(regex_str, line):
    print("匹配成功")

結果

D:\pythonworkspace\regexp\venv\Scripts\python.exe D:/pythonworkspace/regexp/test/test.py
匹配成功

示例

line = "tpr123"
regex_str = "^t.*4$"
if re.match(regex_str, line):
    print("匹配成功")

無結果

  • 非貪婪匹配
?

示例:有一個字符串”line = “tpyyyyyyyppr123” 把 pyyyyyyyp取來出。使用正則表達式的方式。

錯誤示例:

line = "tpyyyyyyyppr123"
regex_str = ".*(p.*p).*"
match_result = re.match(regex_str, line)
if match_result:
    print(match_result.group(1))

運行結果

D:\pythonworkspace\regexp\venv\Scripts\python.exe D:/pythonworkspace/regexp/test/test.py
pp

原因: 正則表達式在匹配的時候是貪婪匹配的,是從字符串的右邊開始對比字符串是否符合正則表達式。 因此取出來的就是pp。下面我們要做的就是讓他從左右取出來。

示例 :

import re

line = "tpyyyyyyyppr123"
regex_str = ".*?(p.*p).*"
match_result = re.match(regex_str, line)
if match_result:
    print(match_result.group(1))

運行結果

D:\pythonworkspace\regexp\venv\Scripts\python.exe D:/pythonworkspace/regexp/test/test.py
pyyyyyyypp

結果還是不符合要求,他把結尾的兩個p都取出來了。 是因爲 .*p這個正則也是符合yyyypp的。如果有三個p 也都會匹配出來。

示例

import re

line = "tpyyyyyyypppr123"
regex_str = ".*?(p.*?p).*"
match_result = re.match(regex_str, line)
if match_result:
    print(match_result.group(1))

運行結果

D:\pythonworkspace\regexp\venv\Scripts\python.exe D:/pythonworkspace/regexp/test/test.py
pyyyyyyyp

這樣結果就符合我們的要求了。
? 的非貪婪模式不只是能把匹配從右開始,還能把當匹配到第一個符合要求的值匹配出來。 就不會在接着匹配了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章