开发者

Actionscript using \Q to ignore specials. Getting strange results

thanks for reading m开发者_高级运维y question.

I am using a RegExp object in actionscript to simply test the occurrence of one string inside another. Sometimes the Strings may contain RegEx special characters, i.e. "*".

To handle that I have been concatenating \Q to the beginning of the search string, like so...

(String(reportItem[attributeToSearch])).search(new RegExp(("\Q" + searchText), "i"))

That is currently working for larger strings and for the string "*". However, I've come across a problem where the String I am searching is "projectiles, with bursting charge". I am search for ",s" and it gives me back -1 as a result. If I search the same thing without the \Q it works fine, but then the "*" case breaks.

What gives?!

Thanks in advance!


You need to escape the \ in the \Q

new RegExp(("\\Q" + searchText), "i");

Try this:

var regExp:RegExp;
regExp = new RegExp("\Qs,", "i");
trace(regExp.toString()); //    /Qs,/i

regExp = /\Qs,/i;               
trace(regExp.toString()); //    /\Qs,/i

regExp = new RegExp("\\Qs,", "i");
trace(regExp.toString()); //    /\Qs,/i


You could escape any special characters in the user's search before including it in the regex using the code below. Unfortunately flex doesn't have any built-in way to escape a regex string.

private function escapeRegex(s:String):String {
   var result:String = s.replace(
      new RegExp("([{}\(\)\^$&.\*\?\/\+\|\[\\\\]|\]|\-)","g"), "\\$1");
   return result;
}

(Thanks to http://www.flexer.info/2008/08/07/how-to-escape-all-regexp-special-chars/ )

You might also consider just using a regular search and toLowerCase if you don't need to take advantage of any regex facilities.

EDIT: As Jacob pointed out, \Q does indeed work and that's a better solution than escaping it manually.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜