re 模組 分組特別說明

2022-06-27 23:18:14 字數 1744 閱讀 6091

from django.test import

testcase

importre#

create your tests here.

ret = re.findall(r"

-?\d+\.\d*|-?\d+

", "

1-2*(60+(-40.35/5)-(-4*3))")

print(ret) #

['1', '-2', '60', '-40.35', '5', '-4', '3']

ret = re.findall(r"

-?\d+\.\d*|(-?\d+)

", "

1-2*(60+(-40.35/5)-(-4*3))")

print(ret) #

['1', '-2', '60', '', '5', '-4', '3']

ret = re.findall(r"

-?\d+|-?\d+\.\d*

", "

1-2*(60+(-40.35/5)-(-4*3))")

print(ret) #

['1', '-2', '60', '-40', '35', '5', '-4', '3']

ret = re.findall(r"

-?\d+|(-?\d+\.\d*)

", "

1-2*(60+(-40.35/5)-(-4*3))")

print(ret) #

['', '', '', '', '', '', '', '']

ret = re.findall(r"

(-?\d+\.\d*)|-?\d+

", "

1-2*(60+(-40.35/5)-(-4*3))")

print(ret) #

['', '', '', '-40.35', '', '', '']

"|" 的匹配順序從左向右 , 而且一旦匹配上了就不會匹配後面的那段正則

"()" 是將被匹配的優先顯示, 但是匹配不中的內容會被用 "" 空字串來表示

先按照整體正則匹配, 然後在提取()中,如果有兩個分組(), 則以元組形式顯示

import

res = "

a b c d"#

p1 = re.compile("\w+\s+\w+")

#print(p1.findall(s)) # ['a b', 'c d']

p1 = re.compile("

(\w+)\s+\w+")

print

(p1.findall(s))

#第一步 ['a b','c d'] # ['(\w+)\s+\w+','(\w+)\s+\w+']

#第二步 ['a','c'] # ['(\w+)', '(\w+)']

p1 = re.compile("

(\w+)\s+(\w+)")

print

(p1.findall(s))

#第一步 ['a b','c d']

# ['(\w+)\s+(\w+)','(\w+)\s+(\w+)']

#第二步 [('a','b'),('c','d')]

re模組和分組 random模組

一,re模組 1.findall search match 查詢,匹配 findall方法括號內引數 正則,字串,返回值是乙個列表,匹配不到返回 空列表 如 ret re.findall s kjewhfqho254qfewgf print ret search 方法括號內引數 正則,字串,匹配到返...

python模組 re模組

匹配任意字元 匹配指定字元類別 字元開頭 字元結尾 取非字元 重複多次字元 0次或多次 重複多次字元 1次或多次 重複單次字元 左右表示式任意匹配 重複m到n次字元 重複m次字元 d 匹配任何十進位制數,相當於 0 9 d 匹配任何非數字字元,相當於 0 9 s 匹配任何空白字元,相當於 fdss ...

subprocess模組 re模組

import subprocess 匯入subprocess模組,該模組的作用為可以通過python 向終端 cmd 傳送命令 while true 進行迴圈,可以讓使用者重複的進行輸入 cmd str input 請輸入終端命令 strip 定義變數cmd str obj subprocess.p...