3 Replies Latest reply on Aug 24, 2011 11:06 PM by Abhishek Chaudhary

    RegExp not working like it should

    TheFlexGuy Level 2

      Maybe I just need another pair of eyes looking at this, but I have a RegExp instance that should work according to multiple tools on the web but it's not matching when it should in my application.  The expression should match if there isn't any leading or trailing spaces.  Here's a code snippet:

       

       

      var regexp:RegExp = new RegExp("^\S.*\S$|^\S(?!.)", "s");
      if(regexp.exec("Hello World") == null)
      {
           trace("NO MATCH");
      }
      

       

       

      Using tools such as Grant Skinners RegExr (http://gskinner.com/RegExr/) it appears that the previous code should get a match.  Does anyone see an issue or know why it isn't working?

        • 1. Re: RegExp not working like it should
          Abhishek Chaudhary

          Hi,

           

           

          var regexp:RegExp = new RegExp("^\S.*\S$|^\S(?!.)", "s");

           

          I think there is some problem with above declaration, declare it in this way and it will work..

           

          var regexp:RegExp = new RegExp(/^\S.*\S$|^\S(?!.)/s);

           

          RegExp constructor has 2 params, one is pattern (string) and other is flag/mode (string), but it doesnt work when we provide a pattern as a string

           

           

          Regards,

          Abhishek Chaudhary

          • 2. Re: RegExp not working like it should
            Stenrap2 Level 1

            In a String, the backslash is interprted as an escape character. You may need to use two backslashes:

             

            var regexp:RegExp = new RegExp("^\\S.*\\S$|^\S(?!.)", "s");
            if(regexp.exec("Hello World") == null)
            {
                 trace("NO MATCH");
            }
            • 3. Re: RegExp not working like it should
              Abhishek Chaudhary Level 1

              Hi All,

               

              while assigning value to a RegEx in constructor itself, we can either specify pattern (for which we need not  escape already escaped character)

               

              like

              var regexp:RegExp = new RegExp(/^\S.*\S$|^\S(?!.)/s)

               

              or we can specify a string (for which we need to escape already escaped characters)

               

              like

               

              var regexp:RegExp = new RegExp("^\\S.*\\S$|^\S(?!.)","s")

               

               

               

              Regards,

              Abihshek Chaudhary