Monday, 15 July 2013

validate with Regex for LRC file in javascript -



validate with Regex for LRC file in javascript -

i have been trying verification of a string contains lrc file http://en.wikipedia.org/wiki/lrc_%28file_format%29

and through regex, verify if format of file right or not. valid, not line starting [mm:ss.xx] [mm:ss] since, default xx=00

so thought homecoming if file corrected or not, including id tags may appear in file.

thanks in advance

i guess need loop on every line in file , test against regex check if matches syntax. if regex ever fails homecoming false. appropriate regex like:

\[[0-9]{2}\:[0-9]{2}(\.[0-9]{2})?\]([\w:\s]+)

which match both:

[00:29.02]line 6 lyrics [00:29]line 6 lyrics

and gives sec matching grouping in case want grab lyrics.

for matching tags want regex along lines of:

\[([a-z]+)\:(.+)\]

which match:

[au:written kal mann / dave appell, 1961] [length: 2:23]

though assumes there no numbers in tag name. gives 2 capturing groups both tag name , value.

in order want have created jsfiddle think demonstrates functionality want. assumes lrc info separated \n characters. illustration method follows:

function test_lrc(str) { var lyric_regex = /\[[0-9]{2}\:[0-9]{2}(\.[0-9]{2})?\](.+)/i; var tag_regex = /\[([a-z]+)\:(.+)\]/i; var lrc = str.split('\n'); var len = lrc.length; var tags = []; var valid = true; (var = 0; < len; i++) { var line = lrc[i].trim(); if (line !== '') { if (tag_regex.test(line)) { var groups = tag_regex.exec(line); tags.push({'tag': groups[1], 'value': groups[2].trim()}); } else if (!lyric_regex.test(line)) { valid = false; break; } } } homecoming { 'valid': valid, 'tags': tags }; }

javascript regex validation

No comments:

Post a Comment