简体   繁体   中英

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+)\\:)?? ).

That seems bizarre behavior. I tried it in http://gskinner.com/RegExr/ which uses flash and http://regexpal.com/ which uses JS

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.

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+)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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