\d 表示一位數字字符? \d{3} 表示3個數字字符
匹配電話比如400-400-1118
import re
phone_number = re.compile(r'\d{3}-\d{3}-\d{4}')
mo = phone_number.search(r'for a number is 400-400-4000')
print(mo.group())
**********************************************************************
phone_number = re.compile(r('(\d{3})-(\d{3})-(\d{4}))? 與之前的區別是進行了簡單的分組
mo = phone_number.search(r'for a number is 400-400-4000')
print(mo.group(0), mo.group(1), mo.group(2))
*************************************************************************
|稱為管道
?表明它前面的分組在這個模式中是可選的
batRegex = re.compile(r'Bat(wp)?man')
mo1 = batRegex.search('The Adventures of Batman')
mo1.group()
*表示匹配0次或多次
如:
bat = re.compile(r'Bat(wo)?man')
mo1 = bat.search(r'Batmanasxas')
mo1.group()? ? ? ? ? ? ? ?->>>>>Batman
mo1 = bat.search(r'Batwowowowowomanasxas')
mo1.group()? ? ? ? ? ? ? ?->>>>>Batwowowowowoman
+表明匹配一次或多次,
{}可以指定匹配的次數? {}通常是貪心匹配,在{}?則是最小匹配方式
\d 匹配數字
\D 除0-9的數字以外的任何字符
\w 在任何字母、數字或下劃線字符
\W 除字母、數字和下劃線以外的任何字符
\s 空格、制表符或換行符
\S 除空格、制表符或換行符
?
[^0123456789] 匹配除了數字之外的字符
?
no = re.compile(r'(.*)')
no.search('Servr the public trust.\n pasdasf\n').group()? ?->>>>>>>>>>>>>Servr the public trust.
no = re.compile(r'(.*), re.DOTALL)
no.search('Servr the public trust.\n pasdasf\n').group() ->>>>>>>>>>>>>>'Servr the public trust.\n pasdasf\n
?
?匹配零次或一次前面的分組。
? *匹配零次或多次前面的分組。
? +匹配一次或多次前面的分組。
? {n}匹配 n 次前面的分組。
? {n,}匹配 n 次或更多前面的分組。
? {,m}匹配零次到 m 次前面的分組。
? {n,m}匹配至少 n 次、至多 m 次前面的分組。
? {n,m}?或*?或+?對前面的分組進行非貪心匹配。
? ^spam 意味著字符串必須以 spam 開始。
? spam$意味著字符串必須以 spam 結束。
? .匹配所有字符,換行符除外。
? \d、 \w 和\s 分別匹配數字、單詞和空格。
? \D、 \W 和\S 分別匹配出數字、單詞和空格外的所有字符。
? [abc]匹配方括號內的任意字符(諸如 a、 b 或 c)。
? [^abc]匹配不在方括號內的任意字符。
no = re.compile(r'robocop', re.I') 可以匹配任意大小寫的字符串
*****************************************************************
def likestrip(text, chuqu=''):
if chuqu == '':
mod = re.compile(r'^*|(\s)*$')
if mod.search(text):
print(mod.sub('', text))
else:
mod = re.compile('^['+chuqu+']*|['+chuqu+']*$')
if mod.search(text):
print(mod.sub('', text))
print(text)
likestrip('wer ', 'w')
編寫一個類似于strip()的函數
?