Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中使用正则表达式获取换行符和制表符组的完全匹配_Python_Regex_Python 3.x - Fatal编程技术网

在python中使用正则表达式获取换行符和制表符组的完全匹配

在python中使用正则表达式获取换行符和制表符组的完全匹配,python,regex,python-3.x,Python,Regex,Python 3.x,代码应该提取\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 special valid = True if len(special.groups()) > 1: # do somethin

代码应该提取\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 special
valid = True
if 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'对象没有属性“groups”

如何搜索相关字符串以获得两个预期组?

使用
re.search
方法将仅返回第一个匹配项,您需要使用
re.findall
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

请参见

在中没有位置。一个最小的完整的可验证的例子谢谢,为什么这不是默认的。人们通常想要一个完整的match@RidhwaanShakeel这实际上是一个非常好的节日。我回答了很多问题,听到人们抱怨在他们的编程语言中没有像
re.findall
这样的方法。