需要特定的 Perl 正则表达式

发布于 2024-09-07 13:07:19 字数 261 浏览 5 评论 0原文

有一个 perl 脚本,需要处理给定目录中某种类型的所有文件。文件应该以 .jup 结尾,并且文件名中不应包含单词“TEMP_”。 IE 应该允许 Corrected.jup,但不允许 TEMP_ Corrected.jup。

已尝试前瞻,但显然模式不正确:

/(?!TEMP_).*\.jup$/

这会返回整个目录内容,包括具有任何扩展名的文件和包含 TEMP_ 的文件,例如文件 TEMP_ Corrected.jup。

Have a perl script that needs to process all files of a certain type from a given directory. The files should be those that end in .jup, and SHOULDN'T contain the word 'TEMP_' in the filename. I.E. It should allow corrected.jup, but not TEMP_corrected.jup.

Have tried a look-ahead, but obviously have the pattern incorrect:

/(?!TEMP_).*\.jup$/

This returns the entire directory contents though, including files with any extension and those containing TEMP_, such as the file TEMP_corrected.jup.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

稚气少女 2024-09-14 13:07:19

您想要的正则表达式是:

/^((?!TEMP_).)*\.jup$/

主要区别是您的正则表达式没有锚定在字符串的开头,因此它匹配满足您的条件的任何子字符串 - 所以在 TEMP_ Corrected.jup 的示例中,子字符串 Corrected.jup 和 EMP_ Corrected.jup 都匹配。

(另一个区别是,将 () 放在前瞻和 . 周围可确保 TEMP_ 不允许出现在字符串中的任何位置,而不是仅仅出现在开头不确定这对您是否重要!)

如果您获取的文件不是 .jup 文件,那么还有另一个问题 - 您的表达式应该只匹配 .jup > 文件。您可以使用以下方法测试您的表达式:

perl -ne 'if(/^((?!TEMP_).)*\.jup$/) {print;}'

然后输入字符串:如果匹配,perl 将回显它们,如果不匹配则不回显。例如:

$ perl -ne 'if(/^((?!TEMP_).)*\.jup$/) {print;}'
foo
foo.jup
foo.jup              <-- perl printed this because 'foo.jup' matched
TEMP_foo.jup

The regular expression you want is:

/^((?!TEMP_).)*\.jup$/

The main difference is that your regular expression is not anchored at the start of the string, so it matches any substring that satisfies your criteria - so in the example of TEMP_corrected.jup, the substrings corrected.jup and EMP_corrected.jup both match.

(The other difference is that putting () round both the lookahead and the . ensures that TEMP_ isn't allowed anywhere in the string, as opposed to just not at the start. Not sure whether that's important to you or not!)

If you're getting files other than .jup files, then there is another problem - your expression should only match .jup files. You can test your expression with:

perl -ne 'if(/^((?!TEMP_).)*\.jup$/) {print;}'

then type strings: perl will echo them back if they match, and not if they don't. For example:

$ perl -ne 'if(/^((?!TEMP_).)*\.jup$/) {print;}'
foo
foo.jup
foo.jup              <-- perl printed this because 'foo.jup' matched
TEMP_foo.jup
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文