正则表达式仅匹配某些文件名 [英] Regex to match only some filenames

查看:94
本文介绍了正则表达式仅匹配某些文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用std :: regex并指定文件路径,我只想匹配以 .txt 结尾的文件名,而不是 _test.txt 形式的文件名或 .txtTEMP .其他任何下划线都可以.

Using std::regex and given a file path, I want to match only the filenames that end with .txt and that are not of the form _test.txt or .txtTEMP. Any other underscore is fine.

例如,

  • somepath/testFile.txt 应该匹配.
  • somepath/test_File.txt 应该匹配.
  • somepath/testFile_test.txt 不匹配.
  • somepath/testFile.txtTEMP 不匹配.
  • somepath/testFile.txt should match.
  • somepath/test_File.txt should match.
  • somepath/testFile_test.txt should not match.
  • somepath/testFile.txtTEMP should not match.

这种模式的正确正则表达式是什么?

What is the correct regex for such a pattern?

我尝试过的事情:

(.*?)(\.txt) --->匹配任何以 .txt 结尾的文件路径.

(.*?)(\.txt) ---> This matches any file path ending with .txt.

要排除包含 _test 的文件,我尝试使用否定的外观:

To exclude files that contains _test I tried to use negative lookahed:

(.*?)(?!_ test)(\.txt)

但这没用.

我还尝试了否定的后向查找,但是MSVC14(Visual Studio 2015)在创建正则表达式时抛出了 std :: regex_error 异常,因此我不确定是否不支持它或我是否正在使用错误的语法.

I also tried negative lookbehind but MSVC14 (Visual Studio 2015) throws a std::regex_error exception when creating the regex, so I'm not sure if it's not supported or I'm using the wrong syntax.

推荐答案

根据您发布的内容,使用此模式

based on what you posted, use this pattern

^(?!.*_).*\.txt$

演示

或基于OP编辑的此模式

or this pattern based on OP edit

^(.*(?<!_test)\.txt$)

演示

这篇关于正则表达式仅匹配某些文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆