代码应该提取\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作为回报。我已经尝试过re.search,re.findall但无法获得 2 个完整的匹配项,因为它正在返回None并且special正在打印: AttributeError: 'NoneType' object has no attribute 'groups'。如何搜索有问题的字符串以获得 2 个预期的组?
1 回答

慕盖茨4494581
TA贡献1850条经验 获得超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
提交
取消