如何为以 .php 结尾的文件创建正则表达式?
我正在尝试编写一个非常简单的正则表达式来匹配任何不以 .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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
几乎:
最后四个点确保在检查前视时有东西可以向前看。
外面的括号是不必要的,因为您对整个匹配感兴趣。
不情愿的
.*?
是不必要的,因为回溯四个步骤比每一步检查以下条件更有效。Almost:
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.有时,在托管语言级别的正则表达式之外使用否定更容易,而不是使用否定先行。在许多语言中,
布尔
补码运算符是一元!
。所以你可以写这样的东西:
根据语言,你也可以完全跳过正则表达式并使用类似的东西(例如Java):
至于原始模式本身的问题:
这匹配,比如说,
file.php,因为
(.*?)
可以捕获file.php
,并且向前看,您无法匹配\ .php
,但您可以匹配$
,所以总的来说这是一个匹配!您可能想要使用“向后查找”,或者如果不支持,您可以在字符串的“开始”处向前查找。这将使用负向先行匹配所有不以
".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:
Depending on language, you can also skip regex altogether and use something like (e.g. Java):
As for the problem with the original pattern itself:
This matches, say,
file.php
, because the(.*?)
can capturefile.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.This will match all strings that does not end with
".php"
using negative lookahead.References
Related questions
(?<=#)[^#]+(?=#)
work?您位于字符串的末尾并向前看。您想要的是向后查找:
请注意,并非所有正则表达式引擎都支持向后查找断言。
You are at the end of the string and looking ahead. What you want is a look behind instead:
Note that not all regular expression engines support lookbehind assertions.