从文件名获取字符串值的正则表达式模式



我坚持用下划线分隔符获取值。我使用preg_match(PHP),但没有得到正确的正则表达式模式。这是文件名的示例模式。

xxxx_get-thisValue_more details_20200728173715594600.zipget-thisValue_more details_20200728173715594600.zipgetThisValue_20200728173715594600.zip

我想要的是在文件名模式上获得get- thisvalue或getThisValue字符串,提前感谢顺便说一下,这是我的代码

<?php 
$filename = 'xxxx_get-thisValue_more details_20200728173715594600.zip';
preg_match('/(.*_)?(.*)_[0-9]+.zip/', $filename, $matches);
echo $prefix = $matches[2];

?比;

例如,您可以使用一个捕获组:

([^_s]+)(?:_[^n_-]+)?_d+.zip$

  • ([^_s]+)捕获组1,匹配除_(或空格)以外的任何字符
  • (?:_[^n_-]+)?可选地匹配_,然后匹配_-以外的任何字符
  • _d+.zip匹配_1 +数字和.zip
  • $字符串结束

Regex演示

例子
$re = '/([^_s]+)(?:_[^n_-]+)?_d+.zip$/m';
$str = 'xxxx_get-thisValue_more details_20200728173715594600.zip
get-thisValue_more details_20200728173715594600.zip
getThisValue_20200728173715594600.zip
xxxx_get-thisValue_more details_20200728173715594600.zip
xxxx_getthisValue_more details_20200728173715594600.zip
1111_get-thisValue_more details_20200728173715594600.zip
1111_getthisValue_more details_20200728173715594600.zip
get-thisValue_more details_20200728173715594600.zip
getthisValue_more details_20200728173715594600.zip
get-thisValue_20200728173715594600.zip
getthisValue_20200728173715594600.zip';
preg_match_all($re, $str, $matches);
print_r($matches[1]);

输出
Array
(
[0] => get-thisValue
[1] => get-thisValue
[2] => getThisValue
[3] => get-thisValue
[4] => getthisValue
[5] => get-thisValue
[6] => getthisValue
[7] => get-thisValue
[8] => getthisValue
[9] => get-thisValue
[10] => getthisValue
)

查看PHP演示。

最新更新