假設有一個字符串,其數據組成方式為:"mode_id1_str_id2",其中id1和id2為任意個數的數字,若存在mode,則id1必然也存在,否則都不存在;id2可有可沒有。
如這些字符串滿足條件:s1 = 'mode_0_string1_1',s2 = 'string2', s3 = 'mode_1_string3' , s4 = 'string4_12'。
目的:去掉mode_id1和id2,也就是去掉滿足某種條件的字符串的前綴和后綴,或者到中間的字符串。如上面的例子中,獲取的字符串分別為:string1、string2、string3、string4。
函數實現如下:
1 s1 = 'mode_0_string1_1' 2 s2 = 'string2' 3 s3 = 'mode_1_string3' 4 s4 = 'string4_12' 5 mode = 'mode' 6 for s in [s1, s2, s3, s4]: 7 prefix = re.match(mode+'_\d+', s) 8 if bool(prefix) == True: 9 prefix_string = prefix.group() 10 prefix_index = len(prefix_string) 11 drop_prefix = s[prefix_index+1:] 12 else: 13 drop_prefix = s 14 # 去掉后綴 15 s_tmp = drop_prefix[::-1] 16 suffix = re.match('\d+_', s_tmp) 17 if bool(suffix) == True: 18 suffix_index = len(suffix.group()) 19 suffix_string = drop_prefix[-suffix_index:] 20 drop_suffix = drop_prefix[:-suffix_index] 21 else: 22 drop_suffix = drop_prefix 23 print (drop_suffix)
輸出結果:
1 string1 2 string2 3 string3 4 string4
這個函數其實沒有普遍的使用意義,在這里只是想說明我們要匹配字符串尾部的字符串時,可以使用string[::-1]的方式先將字符串反過來,再當作處理一般的字符串首部就行了。
