Mike Schilder (mikepictor) wrote in dorkottawa,
Mike Schilder
mikepictor
dorkottawa

Ok, no one said I was an expert at regular expression. I am trying to write a regular expression to search for whole words (so anything bracketed by a non letter or number....so punctuation, space, etc...). The trick is also matching the start and end of line. So far, I haven't been able to figure out how to say "start of line OR punctuation character". Right now, I am just doing multiple searches (see below), and it works great, it just looks clumsy and amateurish (and all things considered, when it comes to regular expressions, I am an amateur).

Please tell me there is a more elegant way to write this search, by which I mean, write it in one expression.


expr = new RegExp('[^a-zA-Z0-9]'+searchString+'[^a-zA-Z0-9]',"gi");
exprST = new RegExp('^'+searchString+'[^a-zA-Z0-9]',"gi");
exprEND = new RegExp('[^a-zA-Z0-9]'+searchString+'$',"gi");
exprALL = new RegExp('^'+searchString+'$',"gi");

srch = sourceText.search(exprST);
if(srch==-1){
srch = sourceText.search(expr);
}
if(srch==-1){
srch = sourceText.search(exprEND);
}
if(srch==-1){
srch = sourceText.search(exprALL);
}
  • Post a new comment

    Error

    default userpic

    Your IP address will be recorded 

  • 7 comments