Regexperry

TorgoX on 2005-02-27T13:01:06

Dear Log,

Yup. I been writin JavaScript.

var haidify_re = /(([kgx])_)/ig;

function haidify (str) {  //   Turns 'ak_a' => ['span',   'a', ['u','k'], 'a' ];

  var  last_string_starts = 0,  treelet = ['span'],  i  ;

  while(1) {
    i = haidify_re.exec(str);
    if(!i) {
      if(last_string_starts != str.length)
       treelet.push( str.substr( last_string_starts ) );
      break;
    } else {
      if(last_string_starts != i.index)
       treelet.push( str.substr( last_string_starts, i.index ) );
      treelet.push( ['u', i[2] ] );
      last_string_starts = i.index + i[1].length;
    }
  }
  return treelet;
}

Interesting thing about JavaScript's RegExp system: it's pretty much a recapitulation of Perl's system, except that there's no $1 vars (instead you look in the array you get from re.exec(str)), and that the regexp cursor isn't on the string, like in Perl's pos($thing); it's instead on the RegExp object, as re.lastIndex.