我们有hello-world-part-2.html
请帮助我构建模式以在php中提取file name before part
和部分number
。
在上面的例子中,我们需要获得
$matches[1] = 'hello-world';
$matches[2] = '2';
答案 0 :(得分:4)
我不知道您使用的语言,但模式应如下:
(.*)-part-(\d+)\.html
答案 1 :(得分:0)
是否值得为此任务使用正则表达式?
为什么不简单地拆分字符串?
foreach (Match match in Regex.Matches("hello-world-part-2", @"([^\x2D]+)")) {
Console.WriteLine(match);
}
在这里你会知道:
所以你只需简单地连接两个:
string filename = match[0] + "-" + match[1];
<?php
$pattern = '/(?P<filename1>[^\-]+)\-(?P<filename2>[^\-]+)\-part\-(?P<number>\d+)(?P<extension>[^$]+)/x';
$input = "hello-world-part-2.html";
preg_match($pattern, $input, $matches, PREG_OFFSET_CAPTURE, 0);
$filename = $matches["filename1"][0] . "-" . $matches["filename2"][0];
$number = $matches["number"][0];
$extension = $matches["extension"][0];
echo "Filename: " . $filename, "\n";
echo "Number: " . $number, "\n";
echo "Extension: " . $extension, "\n";
?>
string longFileName = "hello-world-part-2";
var parts = longFileName.Split(new char[] {'-'});
int position = 0;
string filename = null;
string number = null;
foreach (String part in parts) {
switch (position) {
case 0:
filename += part;
break;
case 1:
filename += "-";
filename += part;
break;
case 3:
number += part;
break;
}
++position;
}
Console.WriteLine(filename);
Console.WriteLine(number);
<?php
$input = "hello-world-part-2.html";
$array = split("-", $input);
$filename;
$number;
for ($i = 0; $i < count($array); $i++) {
switch ($i) {
case 0:
$filename .= $array[$i];
break;
case 1:
$filename .= "-";
$filename .= $array[$i];
break;
case 3:
$str = $array[$i];
$str_array = split("\.", $str);
for ($j = 0; $j < count($str_array); $j++) {
switch ($j) {
case 0:
$number = $str_array[$j];
break;
}
}
break;
}
}
echo $filename, "\n";
echo $number, "\n";
?>
顺便说一下,您最好在标签上指定编程语言,这样我们就可以很方便地为您提供帮助。