Escaping multiple characters in an ActionScript regular expression

北城余情 提交于 2019-12-12 02:59:39

问题


Are there special strings for that, such as \Q and \E in Java? Thanks.


回答1:


As far as I know there is no equivalent to \Q and \E in AS3 RegExp. What you can do is the same thing you would in Javascript: escape special characters for use within a RegExp pattern:

function escapeForRegExp(s:String):String {
    return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
}

// Example:
var s:String = "Some (text) with + special [regex] chars?";
var r:RegExp = new RegExp("^" + escapeForRegExp(s), "g");

// Same as if you wrote the pattern with escaped characters:
/^Some \(text\) with \+ special \[regex\] chars\?/g



回答2:


Short answer is no, you have to escape each characters one at a time with \ as described http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118a9b90204-7e91.html If it is really an issue, you could imagine writing your own escaping function and using: new RegExp(escape("your text (using reserved characters ^^) [...]")) instead of the constant syntax /your text \(using reserved characters \^\^\) \[\.\.\.\]/ If you don't want to escape the whole regex, just concatenate the escaped & non-escaped parts

escape() function could be a RegExp one-liner, just prepending '\' to any reserved character



来源:https://stackoverflow.com/questions/35409971/escaping-multiple-characters-in-an-actionscript-regular-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!