[thelist] regex help

Jeff Howden jeff at jeffhowden.com
Thu Sep 4 19:43:52 CDT 2003


tom,

><><><><><><><><><><><><><><><><><><><><><><><><><><><><><
> From: Tom Dell'Aringa
>
> I have what is probably a simple regex to do but i
> cannot figure it out. Mainly because I need a variable
> in my regex. Here is my target string:
>
> string = "s1s2s3s4";
>
> from there, I need to remove say "s3".
>
> But the 3 is going to be a variable, say personID. so
> really I need to remove "s" + personID as my regex.
>
> How would I do this?
><><><><><><><><><><><><><><><><><><><><><><><><><><><><><

what language?  you don't specify, but from the syntax and what i know about
the languages you use, i'd guess javascript.  if so, my examples which will
be based on javascript will be useful.  if not javascript, consider how to
translate them into whatever language you're using.

so, you have a string "s1s27s3s41s5s16s33" and you need to find and remove
"s3" without also removing "s33".  a simple replace won't work reliably in
this case.  a regex would work, provided it's written so that it doesn't get
too greedy.  i think both of these solutions are the wrong tool for the job.

those that suggested treating it as an s-delimited list are on to something.

  myStudents = 's1s27s3s41s5s16s33';

  myStudent = '3';
  myStudents = myStudents.substring(1).split('s');
               // now equals 1,27,3,41,5,16,33
  myStudentPos = myStudents.indexOf(myStudent);
  myStudents = myStudents.deleteAt(myStudentPos);
  myStudents = 's' + myStudents.join('s');

here's those array methods i use above.

function array_index_of(val)
{
  for(var i = 0; i < this.length; i++)
  {
    if(this[i] == val)
      return i;
  }
  return -1;
}

function array_delete_at(index)
{
  if(index < this.length)
  {
    for(var i = index; i < this.length - 1; i++)
      this[i] = this[i + 1];
    this.length = this.length - 1;
  }
  return this;
}

Array.prototype.indexOf = array_index_of;
Array.prototype.deleteAt = array_delete_at;

good luck,

.jeff

------------------------------------------------------
Jeff Howden - Web Application Specialist
Resume - http://jeffhowden.com/about/resume/
Code Library - http://evolt.jeffhowden.com/jeff/code/




More information about the thelist mailing list