Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Aug 2010
    Southern Oregon
    Thanked 1 Time in 1 Post

    Odd RegExp behavior

    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
    Last edited by anotherJEK; Dec 31st, 2011 at 11:16 PM.

  2. #2
    Senior Coder Logic Ali's Avatar
    Join Date
    Sep 2010
    Thanked 207 Times in 202 Posts
    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 //.

  3. Users who have thanked Logic Ali for this post:

    anotherJEK (Jan 1st, 2012)

  4. #3
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Sydney, Australia
    Thanked 932 Times in 919 Posts
    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

    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts