View Full Version : Odd RegExp behavior

12-31-2011, 11:11 PM
I have been testing regex test string to match the following pattern
(- <any number with/without . decimal point>)
( -[#[.#]] )
here is the code that works the best:

var testStr = '99999+((-25.533) - 5)/99*(-25.533)';
var negValTestStr = new RegExp('\\(\-{1}[0-9]*\.?[0-9]*\\)', 'g');
var test = testStr.match(negValTestStr)

The question is: Why does it only work when the open and close
parenthesis are double escaped: '\\(' and '\\)'
When I use one backslash to escape, it will find -25.533, -5 and -25.533
With two backslashes for escape sequence: (-25.533), (-25.533)

Also, I have to escape the - to get just one -. If I do not escape the -,
-?; which should read - {0, 1} will match --# without escaping -

Thanks for thoughts on this

Logic Ali
01-01-2012, 04:35 AM
You need to escape the backslash for it to be interpreted as an escape character itself.
The RegExp constructor is intended for expressions that require the value of a changing variable or variables included within them. Yours could be constructed within //.

01-01-2012, 11:52 PM
If a regular expression is defined by wrapping it in / / characters then you only need to escape characters once.

If a regular expression is defined using RegExp then the expression starts as a text string and so any \ are string escapes that are applied before the string is converted to a regular expression. So any escapes you want to apply to the expression itself need to be double escaped - one for String and one for RegExp.

So in fact you are missing two backslashes in your expression in order for it to work correctly.

RegExp('\\(\\-{1}[0-9]*\\.?[0-9]*\\)', 'g');

or since that is a constant expression it is easier to define it as