python - python 中的 re.search() 进入无限循环

标签 python regex text-mining regular-language

我正在尝试从文本文档中提取文件路径(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/

相关文章:

python - 在 kivy python 中将按钮的背景更改为不同的形状和样式,如阴影效果等

python - 在圆内寻找轮廓

php - 使用 REGEX 获取查询中的别名列

java.util.regex.PatternSyntaxException : Unclosed character class for\d*

python - Doc2Vec 句子聚类

r - 使用R语料库保留文档ID

python - 如何逐个元素地查找哪个 numpy 数组包含最大值?

python - pg.event.set_allowed([pg.KEYDOWN, pg.KEYUP, pg.QUIT]) pygame.error : video system not initialized

python - 当大写字符前面有小写字符时,如何从字符串末尾删除大写字符?

python - 如何判断两个网页内容是否相似?