1. 程式人生 > 其它 >Datax mysql8.x to mysql8.x json測試樣例

Datax mysql8.x to mysql8.x json測試樣例

一、掃描整個字串並返回:re.search+group

import re

line = "Cats are smarter than dogs"

matchObj = re.search(r'(.*) are (.*?) .*', line, re.M | re.I)   # re.I表示忽略大小寫,re.M表示多行匹配,影響 ^ 和 $

if matchObj:
    print("matchObj.group() : ", matchObj.group())   # 匹配元素
    print("matchObj.group(0) : ", matchObj.group(0))  # 匹配元素
    print(
"matchObj.group(1) : ", matchObj.group(1)) #匹配第1個小組 print("matchObj.group(2) : ", matchObj.group(2)) #匹配第2個小組 print("matchObj.groups() : ", matchObj.groups()) #匹配所有小組 else: print("No match!!")

列印:

matchObj.group() : Cats are smarter than dogs
matchObj.group(0) : Cats are smarter than dogs
matchObj.group(1) : Cats
matchObj.group(2) : smarter
matchObj.groups() : ('Cats', 'smarter')

二、檢索和替換re.sub

import re 

phone = "2004-959-559 # 這是一個國外電話號碼"

num = re.sub(r'#.*$', "", phone) # .*表示匹配所有字元,$表示結尾
print "電話號碼是: ", num
num = re.sub(r'\D', "", phone) # \d表示匹配數字,\D非數字
print "電話號碼是 : ", num

列印:

電話號碼是:  2004-959-559 
電話號碼是 :  2004959559

三、分割:re.split

import re
s = 'cheney, daicy, lucy.'
s_new1 = re.split('\W+', s) # 不包含分割符
print(s_new1)
s_new2 = re.split('(\W+)', s) # 包含分割符
print(s_new2)
s_new3 = re.split('\W+', s, 1) # 只分割一次
print(s_new3)

列印:

['cheney', 'daicy', 'lucy', '']
['cheney', ', ', 'daicy', ', ', 'lucy', '.', '']
['cheney', 'daicy, lucy.']

四、分組匹配轉字典:(?P...)+groupdict()

import re
s = '1102231990xxxxxxxx'
res = re.search('(?P<province>\d{3})(?P<city>\d{3})(?P<born_year>\d{4})',s)
print(res.groupdict())

列印:{'province': '110', 'city': '223', 'born_year': '1990'}

五、模式元素含義

^:匹配字串的開頭

$:匹配字串的末尾

.:匹配任意字元,除了換行符

[amk]:匹配 'a','m'或'k'

[^amk]:匹配 'a','m'或'k'之外的字元

*:匹配0個或多個的表示式

+:匹配1個或多個的表示式

?:匹配0個或1個由前面的正則表示式定義的片段,非貪婪方式

\w:匹配字母數字及下劃線

\W:匹配非字母數字及下劃線

\s:匹配任意空白字元,等價於[ \t\n\r\f]

\d:匹配任意數字,等價於 [0-9].

w:匹配字母數字及下劃線

w:匹配字母數字及下劃線

w:匹配字母數字及下劃線

六、例項:

a.*?b:匹配最短的以a開頭b結束的字串,比如aabab,可以匹配到aab和ab

^[0-9].*[0-9]$:匹配以數字開頭和結尾的字串,中間任意

import re

mobile = '18312423454'
# 3種符合條件情況:
#   13、15、18開頭11位數字
#   147開頭11位
#   179開頭11位          
MOBILE = "^1[358]\d{9}$|^147\d{8}$|^179\d{8}$"  

if re.match(MOBILE,mobile):
    print(mobile)