代碼應該提取\n\t組。它總是以開頭\n但\t可以是 0 或更多,在它們之間有子字符串def longestAbsolutePath(string):...paths[path] = r'dir\n\tsubdir1\n\t\tfile1'special = re.search(r'(\\n(\\t)*)',paths[path])print specialvalid = Trueif len(special.groups()) > 1: # do something...return longest在上面的測試字符串中dir\n\tsubdir1\n\t\tfile1,我期望得到\n\t并\n\t\t作為回報。我已經(jīng)嘗試過re.search,re.findall但無法獲得 2 個完整的匹配項,因為它正在返回None并且special正在打?。?AttributeError: 'NoneType' object has no attribute 'groups'。如何搜索有問題的字符串以獲得 2 個預期的組?
1 回答

慕蓋茨4494581
TA貢獻1850條經(jīng)驗 獲得超11個贊
該re.search方法將僅返回第一個匹配項,您需要使用re.findallor re.finditer。此外,該模式最好使用非捕獲組 , 來編寫(?:...),因為您之后不使用該值,并且re.findall如果使用此方法會弄亂輸出。
paths[path] = r'dir\n\tsubdir1\n\t\tfile1'
special = re.findall(r'\\n(?:\\t)*', paths[path])
if len(special) > 1:
# do something
添加回答
舉報
0/150
提交
取消