我不太确定,如果这可能是你想要捕捉的。但是,原因是您可能希望使用捕获组来包装字符串,以便于获取。例如,此表达式示例捕获组如何围绕您想要的字符工作:
^([0-9]+\n|)([0-9:,->\s]+)
这可能不是这样做的方式,也可能不是最好的表达方式。但是,它可能会给您一个以不同方式解决问题的想法。
我猜你可能想要捕获日期时间线和之前的线,它们可能有也可能没有数字。
图形
此图显示了表达式的工作原理,您可以在此链接中可视化其他表达式:
在将数据发送到 RegEx 引擎之前,您可能需要编写一个脚本来清理数据,这样您就有一个简单的表达式。
使用 JavaScript 进行示例测试
const regex = /^([0-9]+\n|)([0-9:,->\s]+)/mg;
const str = `1
00:00:04,019 --> 00:00:07,299
line1
line2
2
00:00:07,414 --> 00:00:09,155
line1
00:00:09,276 --> 00:00:11,429
line1
00:00:11,549 --> 00:00:14,874
line1
line2
`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
PHP 测试
这可能不会产生您想要的输出,这只是一个示例:
$re = '/^([0-9]+\n|)([0-9:,->\s]+)/m';
$str = '1
00:00:04,019 --> 00:00:07,299
line1
line2
2
00:00:07,414 --> 00:00:09,155
line1
00:00:09,276 --> 00:00:11,429
line1
00:00:11,549 --> 00:00:14,874
line1
line2
';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
foreach ($matches[0] as $key => $value) {
if ($value == "") {
unset($matches[0][$key]);
} else {
$matches[0][$key] = trim($value);
}
}
var_dump($matches[0]);
性能测试
这个 JavaScript 片段使用简单的 100 万次for
循环显示了该表达式的性能。
repeat = 1000000;
start = Date.now();
for (var i = repeat; i >= 0; i--) {
var string = '2 \n00:00:07,414 --> 00:00:09,155';
var regex = /(.*)([0-9:,->\s]+)/gm;
var match = string.replace(regex, "$2");
}
end = Date.now() - start;
console.log("YAAAY! \"" + match + "\" is a match ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. ");
如果您希望在一个变量中捕获所有所需的输出,您可以简单地在整个表达式周围添加一个捕获组,然后使用$1
.
如果需要,您还可以添加或减少边界,例如这个。
^(?:[0-9]+\n|\n)(([0-9:,]+)([\s->]+)([0-9:,]+))$
使用 JavaScript 测试第二个表达式的示例
const regex = /^(?:[0-9]+\n|\n)(([0-9:,]+)([\s->]+)([0-9:,]+))$/gm;
const str = `1
00:00:04,019 --> 00:00:07,299
- cdcdc
- cddcd
2
00:00:07,414 --> 00:00:09,155
54564
00:00:09,276 --> 00:00:11,429
- 445454 - ccd
- cdscdcdcd
00:00:11,549 --> 00:00:14,874
line1
line2
`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}