如何为以 .php 结尾的文件创建正则表达式?

发布于 2024-09-12 23:50:42 字数 145 浏览 2 评论 0原文

我正在尝试编写一个非常简单的正则表达式来匹配任何不以 .php 结尾的文件名。我想出了以下内容...

(.*?)(?!\.php)$

...但是这与所有文件名匹配。如果有人能指出我正确的方向,我将非常感激。

I'm trying to write a very simple regular expression that matches any file name that doesn't end in .php. I came up with the following...

(.*?)(?!\.php)$

...however this matches all filenames. If someone could point me in the right direction I'd be very grateful.

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

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

发布评论

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

评论(3

一个人的旅程 2024-09-19 23:50:42

几乎:

.*(?!\.php)....$

最后四个点确保在检查前视时有东西可以向前看

外面的括号是不必要的,因为您对整个匹配感兴趣。

不情愿的 .*? 是不必要的,因为回溯四个步骤比每一步检查以下条件更有效。

Almost:

.*(?!\.php)....$

The last four dots make sure that there is something to look ahead at, when the look-ahead is checked.

The outer parentheses are unnecessary since you are interested in the entire match.

The reluctant .*? is unnecessary, since backtracking four steps is more efficient than checking the following condition with every step.

≈。彩虹 2024-09-19 23:50:42

有时,在托管语言级别的正则表达式之外使用否定更容易,而不是使用否定先行。在许多语言中,布尔补码运算符是一元!

所以你可以写这样的东西:

! str.hasMatch(/\.php$/)

根据语言,你也可以完全跳过正则表达式并使用类似的东西(例如Java):

! str.endsWith(".php")

至于原始模式本身的问题:

(.*?)(?!\.php)$   // original pattern, doesn't work!

这匹配,比如说,file.php,因为 (.*?) 可以捕获 file.php,并且向前看,您无法匹配 \ .php,但您可以匹配 $,所以总的来说这是一个匹配!您可能想要使用“向后查找”,或者如果不支持,您可以在字符串的“开始”处向前查找。

^(?!.*\.php$).*$  // negative lookahead, works

这将使用负向先行匹配所有不以 ".php" 结尾的字符串。

参考文献

相关问题

Instead of using negative lookahead, sometimes it's easier to use the negation outside the regex at the hosting language level. In many languages, the boolean complement operator is the unary !.

So you can write something like this:

! str.hasMatch(/\.php$/)

Depending on language, you can also skip regex altogether and use something like (e.g. Java):

! str.endsWith(".php")

As for the problem with the original pattern itself:

(.*?)(?!\.php)$   // original pattern, doesn't work!

This matches, say, file.php, because the (.*?) can capture file.php, and looking ahead, you can't match \.php, but you can match a $, so altogether it's a match! You may want to use look behind, or if it's not supported, you can lookahead at the start of the string.

^(?!.*\.php$).*$  // negative lookahead, works

This will match all strings that does not end with ".php" using negative lookahead.

References

Related questions

和影子一齐双人舞 2024-09-19 23:50:42

您位于字符串的末尾并向前看。您想要的是向后查找:

(.*)$(?<!\.php)

请注意,并非所有正则表达式引擎都支持向后查找断言。

You are at the end of the string and looking ahead. What you want is a look behind instead:

(.*)$(?<!\.php)

Note that not all regular expression engines support lookbehind assertions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文