问题
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