我正在尝试从文本文档中提取文件路径(Windows/Ubuntu,相对/绝对)。
下面的正则表达式代码用于检查一个单词是否为文件路径。
它适用于大多数情况,但在一种情况下会失败,因为它会进入无限循环。对此有什么解释吗?
import re
path_regex = re.compile(r'^([\.]*)([/]+)(((?![<>:"/\\|?*]).)+((?<![ .])(\\|/))?)*$' , re.I)
text = '/var/lib/jenkins/jobs/abcd-deploy-test-environment-oneccc/workspace/../workspace/abcd-deploy-test-environment.sh'
path_regex.search(text)
最佳答案
确实有问题。
您已经覆盖了与虚假量词混合的子表达式。
修改了斜线之间的必需部分
使用这个很容易修复 ^([\.]*)([/]+)((?:[^<>:"/\\|?*.\r\n]|\.(?![\\/]))[\\/]?)*$
这个想法是要看看你在防范什么。
守卫是,如果前面没有点,则允许使用正斜线或反斜线。
因此,您必须在排除类中包含 点 和\和/
然后在单独的交替中对它们进行限定。
如果你这样做,它总是会通过的。
^
( [\.]* ) # (1)
( [/]+ ) # (2)
( # (3 start)
(?: # Group start (required between slashes)
[^<>:"/\\|?*.\r\n] # Any character, but exclude these
| # or,
\. # The dot, if not followed by forward or back slash
(?! [\\/] )
) # Group end
[\\/]? # Optional forward or back shash
)* # (3 end)
$
关于python - python 中的 re.search() 进入无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42374498/