简体   繁体   English

当h和m是可选的时,正则表达式获取歌曲h:m:s

[英]Regex get song h:m:s when h and m is optional

Pattern: 图案:

(.*?) (?:(\d+)\:)??(?:(\d+)\:)??(\d+)

Input 输入

song1.mp3 2:35
song2.mp3 1:2:45
song3.mp3 45

Replace: 更换:

the song "$1" is $3min and $4sec

Result I want 我想要的结果

the song "song1.mp3" is 2min and 35sec
the song "song2.mp3" is 2min and 45sec
the song "song3.mp3" is min and 45sec

What happens is the minute part attempts to not happen and for some reason the leftmost nongreedy pattern ( .*? ) before space happens instead of the rightmost nongreedy pattern ( (?:(\\d+)\\:)?? ). 发生的是微小的部分企图不发生,并且由于某种原因,在出现空间之前最左边的非贪婪模式( .*? )代替了最右边的非贪婪模式( (?:(\\d+)\\:)?? )。

That seems bizarre behavior. 这似乎是奇怪的行为。 I tried it in http://gskinner.com/RegExr/ which uses flash and http://regexpal.com/ which uses JS 我在使用Flash的http://gskinner.com/RegExr/和使用JS的http://regexpal.com/中进行了尝试

I can fix it using $ at the end but what if I don't want to match the end? 我可以在末尾使用$来修复它,但是如果我不想匹配末尾怎么办? .*$ breaks it. .*$破坏了它。

I mostly care about .NET and JS solutions. 我主要关心.NET和JS解决方案。

The following seems to work for all of your examples, replace matches of: 以下似乎适用于您的所有示例,替换以下项的匹配项:

(.*?) (\d+:)?(\d+):(\d+)

with: 有:

the song "$1" is $3min and $4sec

试试这个模式:

(?<song>[^ ]+) (?:(?:(?<h>\d+):)?(?:(?<m>\d+):))?(?<s>\d+)

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

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