简体   繁体   English

正则表达式沮丧试图找到与模式匹配的文件名

[英]Regex frustration trying to find filename that matches pattern

I suck at regex. 我在正则表达式上很烂。 I have a php function that will read through a directory of filenames on my server, and I am trying to pull out filename data from one specific filename, but am failing miserably. 我有一个php函数,它将读取服务器上文件名的目录,并且我试图从一个特定的文件名中提取文件名数据,但失败了。 Here is what I have thus far: 到目前为止,这是我所拥有的:

$file = 'VERSION_3.7.1b.txt';
$VersionNumber = preg_match('#^(VERSION_)[^\s]*\.\.[^\s]+(\.(txt))#', $file);

I am trying to have the preg_match only return true for files that begin with 'VERSION_' and end with '.txt. 我试图让preg_match仅对以'VERSION_'开头和'.txt结尾的文件返回true。 The stuff in the middle may be any variety of numbers, letters, periods...and that is the part I want to return. 中间的东西可能是任何数字,字母,句号……这就是我要返回的部分。 So in this case, I want $VersionNumber to end up set as '3.7.1b' 因此,在这种情况下,我希望将$ VersionNumber最终设置为“ 3.7.1b”

Other filenames that would return something are like these: 其他会返回以下内容的文件名如下:

VERSION_3.txt  ->  3
VERSION_3.7.txt  ->  3.7
VERSION_3.7e.1.txt  ->  3.7e.1
VERSION_2012.09.13.3.7.1b.txt  ->  2012.09.13.3.7.1b
VERSION_3.7.20120913.txt  ->  3.7.20120913

Any regex masters out there that can explain to me if I am even close? 是否有正则表达式高手可以向我解释一下我是否接近? Thanks! 谢谢!

You'll want to pass a variable for $matches as well. 您还需要为$ matches传递一个变量。

I simplified your RegExp. 我简化了您的RegExp。 Try this: 尝试这个:

$file = 'VERSION_3.7.1b.txt';
preg_match('/^VERSION_(.*?)\.txt/', $file, $matches);
echo $matches[1];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM