2

Earlier questions on StackOverflow discuss escaping for JavaScript regular expressions, e.g.:

An implementation suggested is the following:

RegExp.quote = function(str) {
     return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
};

Given that regular expressions in the two languages are not identical, is anyone aware of a JavaScript method that properly escapes strings to be used for Java regular expressions?

Community
  • 1
  • 1
PNS
  • 19,295
  • 32
  • 96
  • 143

1 Answers1

2

There's no need for any escaping at all. Those questions are about what needs to be done when the regular expression is being constructed as a string in the source language. Since you're reading the string from an input field, there's no layer of interpretation to worry about.

Just send the string to the server, where it will be discovered to be a valid regex or not.

edit — though I can't think of any, the real thing to worry about might be any sort of "injection" attack that could be conducted through this avenue. Seems to me that if you're just passing a regex to Pattern.compile() there aren't any side-effect channels that could be exploited.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • You are right about the injection attack and about the "no interpretation" case, so I modified the question to just focus on the JavaScript code, which was the main topic. Thanks! – PNS Dec 29 '12 at 00:40
  • @PNS ok. Well there's no built-in JavaScript function for dealing with Java *anything*. Doing a replace like that would be appropriate if the person entering the regular expression expected to be able to use normal regex syntax. The only thing I'm not sure about is `?` because of things like `(?: ... )` in regex syntax. – Pointy Dec 29 '12 at 00:43