我因为这个问题掉了很多头发。 我有一个从“1”到“999”不等的输入字符串。 此值表示以分钟为单位的视频片段的运行时间。 我需要将字符串转换为以小时和分钟表示的相同持续时间。 例如:
"97" needs to become "1h 37m"
"123" needs to become "2h 3m"
"231" needs to become "3h 51m"
我需要用正则表达式(PHP 7.4 中的 PCRE)来实现它。 不幸的是,我不能用 PHP 对此进行编程,所以我仅限于正则表达式模式。 我得到了 coding: (\d+) 用于输入字符串匹配部分。 然后我想到正则表达式操作字符串和 AFAIK 无法比较 反对数值。否则我可以用以下方法解决这个问题(用伪代码):
int( [input var] / 60 ) = [hours]
[input var] modulus 60 = [mins]
print "[hours]h [mins]m"
因为我不能使用它,所以我不知道要指定什么作为正则表达式的替换模式。 请帮助。
使用 Raku(以前称为 Perl_6)
注意我无法用 PHP 解决您的问题,但也许这个 Raku 代码可以提供一些指导?
~$ raku -pe 's/ ^ \" <( \d+ )> /{ (($/.Int / 60).Int, "h ", $/.Int % 60, "m").join }/;' file
#OR
~$ raku -pe 's/ ^ \" <( \d+ )>/{($/.Int / 60).Int}h {$/.Int % 60}m/;' file
基本上,您编写一个单行代码,通过自动打印逐行检查您的文件
-pe
。使用传统的 s///
替换运算符(对于多个替换,使用 s:g///
即 :global)。
\d+
原子<(
... )>
{
...}
代码块来计算替换。$/
捕获到Int
,除以60
,取Int
那个%
模运算符来获得余数h
和m
,join
删除空格(如有必要)。样本输入:
"97" needs to become "1h 37m"
"123" needs to become "2h 3m"
"231" needs to become "3h 51m"
样本输出:
"1h 37m" needs to become "1h 37m"
"2h 3m" needs to become "2h 3m"
"3h 51m" needs to become "3h 51m"
HTH.