php PCRE 正则表达式仅获取以 .txt 结尾的文件名
所以我试图在 php 中形成一个 PCRE 正则表达式,专门与 preg_replace 一起使用,它将匹配组成文本(.txt)文件名的任意数量的字符,从中我将导出文件的目录。
我最初的方法是定义终止 .txt 字符串,然后尝试为除 / 或 \ 之外的每个字符指定字符匹配,所以我最终得到了类似的结果:
'/[^\\\\/]*\.txt$/'
但这似乎根本不起作用,我认为它可能会将否定解释为 demorgan 的形式,又名: (A+B)' <=> A'B'
但是在尝试这个测试之后:
'/[^\\\\]\|[^/]*\.txt$/'
我得到了相同的结果,这让我认为我不应该转义或运算符(|),但这也无法匹配。有人知道我做错了什么吗?
so I am trying to form a PCRE regex in php, specifically for use with preg_replace, that will match any number of characters that make up a text(.txt) file name, from this I will derive the directory of the file.
my initial approach was to define the terminating .txt string, then attempt to specify a character match on every character except for the / or \, so I ended up with something like:
'/[^\\\\/]*\.txt$/'
but this didn't seem to work at all, I assume it might be interpreting the negation as the demorgan's form aka:
(A+B)' <=> A'B'
but after attempting this test:
'/[^\\\\]\|[^/]*\.txt$/'
I came to the same result, which made me think that I shouldn't escape the or operator(|), but this also failed to match. Anyone know what I'm doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下正则表达式应该适用于获取 .txt 文件的文件名:
工作原理:
.*
是贪婪的,因此会强制匹配尽可能靠右。[\\\\/]
确保文件名前面有一个\
或/
。(.*?\.txt)
使用非贪婪匹配来确保文件名尽可能小,后面跟上.txt
,将其捕获到组 1。The foloowing regular expression should work for getting the filename of .txt files:
How it works:
.*
is greedy and thus forces match to be as far to the right as possible.[\\\\/]
ensures that we have a\
or/
in front of the filename.(.*?\.txt)
uses non-greedy matching to ensure that the filename is as small as possible, followed by.txt
, capturing it into group 1.$
forces match to be at end of string.试试这个模式
'/\b(?P[\w-.]+\.txt)\b/mi'
Try this pattern
'/\b(?P<files>[\w-.]+\.txt)\b/mi'