How to build a regular expression on runtime?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Harry

    #1

    How to build a regular expression on runtime?

    Hi there,

    does anyone know how I can build a regular expression e.g. for the
    string.search() function on runtime, depending on the content of
    variables? Should be something like this:

    var strkey = "something" ;
    var str = "Somethin like this";

    if( str.search( / + strkey + / ) > -1 )
    {
    ...
    }

    TIA
    Harry
  • Michael Winter

    #2
    Re: How to build a regular expression on runtime?

    On 16 Aug 2004 09:15:34 -0700, Harry <harald.humml @t-systems.at> wrote:
    [color=blue]
    > does anyone know how I can build a regular expression e.g. for the
    > string.search() function on runtime, depending on the content of
    > variables?[/color]

    [snip]

    Use the regular expression constructor to create an object:

    var re = new RegExp(pattern, flags);
    var str = str.replace(re, replacement);

    Both pattern and flags are strings (flags is optional), so remember to
    escape characters properly. For example,

    /\d/ becomes '\\d'

    Notice that the forward slashes aren't present in the pattern.

    Good luck,
    Mike

    --
    Michael Winter
    Replace ".invalid" with ".uk" to reply by e-mail

    Comment

    • Alberto

      #3
      Re: How to build a regular expression on runtime?

      Proceed as follows (one suggestion out of many of course):

      <script><!--
      var test_string="ha llo guy hallo! I said hallo!";
      var yourRegExp_as_t ext="\\w{5}"; //that checks for 5 letters long words
      var regExpObject=ne w RegExp();
      //now use the built in method compile
      regExpObject.co mpile(yourRegEx p_as_text, "gi");
      /*the second argument takes in the so called modifiers. g stands fopr GLOBAL
      scope (search ALL the occurrencies, that is), i stands for case INsensitive
      search*/

      //Now you have a valid regular expression
      //use it with methods that are regular expression methods, instance
      replace():
      test_string=tes t_string.replac e(regExpObject, "HI"); /*replaced hallo with
      HI*/
      alert(test_stri ng)
      //--></script>

      For an overview of the javascript methods that deal with regular expressions
      (NOT the best summary available online of course! just one among many
      others!):


      I hope this helps
      ciao
      Alberto







      "Harry" <harald.humml @t-systems.at> ha scritto nel messaggio
      news:b3271585.0 408160815.4ef7c 45@posting.goog le.com...[color=blue]
      > Hi there,
      >
      > does anyone know how I can build a regular expression e.g. for the
      > string.search() function on runtime, depending on the content of
      > variables? Should be something like this:
      >
      > var strkey = "something" ;
      > var str = "Somethin like this";
      >
      > if( str.search( / + strkey + / ) > -1 )
      > {
      > ...
      > }
      >
      > TIA
      > Harry[/color]


      Comment

      • Alberto

        #4
        Re: How to build a regular expression on runtime?

        PS if the line

        //use it with methods that are regular expression methods, instance
        replace():

        gets broken like it does on my reader, eliminate that ISOLATED replace():
        that was not code but a part of a comment

        ciao
        Alberto

        "Alberto" <nospam@nospam. nospam> ha scritto nel messaggio
        news:Jn8Uc.1457 62$5D1.7196307@ news4.tin.it...[color=blue]
        > Proceed as follows (one suggestion out of many of course):
        >
        > <script><!--
        > var test_string="ha llo guy hallo! I said hallo!";
        > var yourRegExp_as_t ext="\\w{5}"; //that checks for 5 letters long words
        > var regExpObject=ne w RegExp();
        > //now use the built in method compile
        > regExpObject.co mpile(yourRegEx p_as_text, "gi");
        > /*the second argument takes in the so called modifiers. g stands fopr[/color]
        GLOBAL[color=blue]
        > scope (search ALL the occurrencies, that is), i stands for case[/color]
        INsensitive[color=blue]
        > search*/
        >
        > //Now you have a valid regular expression
        > //use it with methods that are regular expression methods, instance
        > replace():
        > test_string=tes t_string.replac e(regExpObject, "HI"); /*replaced hallo[/color]
        with[color=blue]
        > HI*/
        > alert(test_stri ng)
        > //--></script>
        >
        > For an overview of the javascript methods that deal with regular[/color]
        expressions[color=blue]
        > (NOT the best summary available online of course! just one among many
        > others!):
        > http://www.unitedscripters.com/spellbinder/regexp.html
        >
        > I hope this helps
        > ciao
        > Alberto
        > http://www.unitedscripters.com/
        >
        >
        >
        >
        >
        >
        > "Harry" <harald.humml @t-systems.at> ha scritto nel messaggio
        > news:b3271585.0 408160815.4ef7c 45@posting.goog le.com...[color=green]
        > > Hi there,
        > >
        > > does anyone know how I can build a regular expression e.g. for the
        > > string.search() function on runtime, depending on the content of
        > > variables? Should be something like this:
        > >
        > > var strkey = "something" ;
        > > var str = "Somethin like this";
        > >
        > > if( str.search( / + strkey + / ) > -1 )
        > > {
        > > ...
        > > }
        > >
        > > TIA
        > > Harry[/color]
        >
        >[/color]


        Comment

        • Harry

          #5
          Re: How to build a regular expression on runtime?

          Alberto,
          Michael,

          Thank you for your replies. The Problem is not to replace a string
          with regexp. The Problem is to build a search-regexp dynamically at
          runtime. Naturally I will search with regexp like this:

          var somestring = "someconten t";
          if( somestring.sear ch( /some/ ) > -1 )
          {
          ...
          }

          In this example, the problem is that the searchstring is hardcoded.
          What I want is:

          var somestringarray = new Array( "one", "two", "three" );
          var somestring = "This is one of my favorite";
          for( var i = 0; i < somestringarray .length; i++ )
          {
          if( somestring.sear ch( somestringarray[ i ] ) > -1 )
          {
          ...
          break;
          }
          }

          How can I achieve this?

          TIA
          Harry

          "Alberto" <nospam@nospam. nospam> wrote in message news:<Hr8Uc.145 776$5D1.7197081 @news4.tin.it>. ..[color=blue]
          > PS if the line
          >
          > //use it with methods that are regular expression methods, instance
          > replace():
          >
          > gets broken like it does on my reader, eliminate that ISOLATED replace():
          > that was not code but a part of a comment
          >
          > ciao
          > Alberto
          >
          > "Alberto" <nospam@nospam. nospam> ha scritto nel messaggio
          > news:Jn8Uc.1457 62$5D1.7196307@ news4.tin.it...[color=green]
          > > Proceed as follows (one suggestion out of many of course):
          > >
          > > <script><!--
          > > var test_string="ha llo guy hallo! I said hallo!";
          > > var yourRegExp_as_t ext="\\w{5}"; //that checks for 5 letters long words
          > > var regExpObject=ne w RegExp();
          > > //now use the built in method compile
          > > regExpObject.co mpile(yourRegEx p_as_text, "gi");
          > > /*the second argument takes in the so called modifiers. g stands fopr[/color]
          > GLOBAL[color=green]
          > > scope (search ALL the occurrencies, that is), i stands for case[/color]
          > INsensitive[color=green]
          > > search*/
          > >
          > > //Now you have a valid regular expression
          > > //use it with methods that are regular expression methods, instance
          > > replace():
          > > test_string=tes t_string.replac e(regExpObject, "HI"); /*replaced hallo[/color]
          > with[color=green]
          > > HI*/
          > > alert(test_stri ng)
          > > //--></script>
          > >
          > > For an overview of the javascript methods that deal with regular[/color]
          > expressions[color=green]
          > > (NOT the best summary available online of course! just one among many
          > > others!):
          > > http://www.unitedscripters.com/spellbinder/regexp.html
          > >
          > > I hope this helps
          > > ciao
          > > Alberto
          > > http://www.unitedscripters.com/
          > >
          > >
          > >
          > >
          > >
          > >
          > > "Harry" <harald.humml @t-systems.at> ha scritto nel messaggio
          > > news:b3271585.0 408160815.4ef7c 45@posting.goog le.com...[color=darkred]
          > > > Hi there,
          > > >
          > > > does anyone know how I can build a regular expression e.g. for the
          > > > string.search() function on runtime, depending on the content of
          > > > variables? Should be something like this:
          > > >
          > > > var strkey = "something" ;
          > > > var str = "Somethin like this";
          > > >
          > > > if( str.search( / + strkey + / ) > -1 )
          > > > {
          > > > ...
          > > > }
          > > >
          > > > TIA
          > > > Harry[/color]
          > >
          > >[/color][/color]

          Comment

          • Evertjan.

            #6
            Re: How to build a regular expression on runtime?

            Harry wrote on 17 aug 2004 in comp.lang.javas cript:
            [color=blue]
            > In this example, the problem is that the searchstring is hardcoded.
            > What I want is:
            >
            > var somestringarray = new Array( "one", "two", "three" );
            > var somestring = "This is one of my favorite";
            > for( var i = 0; i < somestringarray .length; i++ )
            > {
            > if( somestring.sear ch( somestringarray[ i ] ) > -1 )
            > {
            > ...
            > break;
            > }
            >[/color]

            re = new RegExp(somestri ngarray[i],"i")
            if (somestring.sea rch(re)>=0)

            --
            Evertjan.
            The Netherlands.
            (Please change the x'es to dots in my emailaddress)

            Comment

            • Thomas 'PointedEars' Lahn

              #7
              Re: How to build a regular expression on runtime?

              Harry wrote:
              [color=blue]
              > [...] The Problem is to build a search-regexp dynamically at
              > runtime. Naturally I will search with regexp like this:
              >
              > var somestring = "someconten t";
              > if( somestring.sear ch( /some/ ) > -1 )
              > {
              > ...
              > }
              >
              > In this example, the problem is that the searchstring is hardcoded.
              > What I want is:
              >
              > var somestringarray = new Array( "one", "two", "three" );
              > var somestring = "This is one of my favorite";
              > for( var i = 0; i < somestringarray .length; i++ )
              > {
              > if( somestring.sear ch( somestringarray[ i ] ) > -1 )
              > {
              > ...
              > break;
              > }
              > }
              >
              > How can I achieve this?[/color]

              if (new RegExp(somestri ngarray[i]).test(somestri ng))
              {
              ...
              }

              You should be aware that Regular Expressions may contain special characters
              (".", "?" etc.) You must escape them in somestringarray[i] prior if they
              should not have their special meaning, i.e. you must work on a ruleset of
              RegExps allowed for your users. If no RegExp at all is allowed for input,
              use the escapeRE() method I posted a few days before.

              And if you do not search for patterns, but only for strings, you should use
              String.prototyp e.indexOf() instead, not requiring any RegExp object, which
              is usually faster.
              [color=blue]
              > [Top post][/color]

              Please don't, see the <http://jibbering.com/faq/>.


              PointedEars

              P.S.: de.comp.lang.ja vascript exists.
              --
              Let's introduce General Protection to Corporal Punishment

              Comment

              • Alberto

                #8
                Re: How to build a regular expression on runtime?

                Hello

                it doesn't matter whether you want to replace or search: what you basically
                need is to compile a regular expression on the run, ISN'T IT?
                Try the code I sent to you:

                <script><!--
                var test_string="ha llo guy hallo! I said hallo!";
                var yourRegExp_as_t ext="\\w{5}"; //that checks for 5 letters long words
                var regExpObject=ne w RegExp();
                //now use the built in method compile
                regExpObject.co mpile(yourRegEx p_as_text, "gi");
                /*the second argument takes in the so called modifiers. g stands fopr GLOBAL
                scope (search ALL the occurrencies, that is), i stands for case INsensitive
                search*/

                //Now you have a valid regular expression
                /*use it with methods that are regular expression methods, instance
                replace():*/
                test_string=tes t_string.replac e(regExpObject, "HI"); /*replaced hallo with
                HI*/
                alert(test_stri ng)
                //--></script>

                Once you don't need replacing, that's not a problem, you can use search:
                test_string.seR CH(regExpObject );

                You'd have to work a bit yourself on the codes sent as a reply.
                Anyway, to get closer to your needs:

                <script><!--
                var somestringarray = new Array( "one", "two", "three" );
                var somestring = "This is one of my favorite";
                var regExpObject=ne w RegExp();
                for( var i = 0; i < somestringarray .length; i++ )
                {
                regExpObject.co mpile(somestrin garray[i], "gi");
                if( somestring.matc h( regExpObject ))
                {alert(somestri ngarray[i])
                break;
                }
                }
                //--></script>

                ciao
                Alberto





                Comment

                • Harry

                  #9
                  Re: How to build a regular expression on runtime?

                  Hi,

                  Ok, I´ve it now. Thank you all for the helpful replies. Great forum!

                  Harry



                  "Alberto" <nospam@nospam. nospam> wrote in message news:<FmqUc.148 822$5D1.7342145 @news4.tin.it>. ..[color=blue]
                  > Hello
                  >
                  > it doesn't matter whether you want to replace or search: what you basically
                  > need is to compile a regular expression on the run, ISN'T IT?
                  > Try the code I sent to you:
                  >
                  > <script><!--
                  > var test_string="ha llo guy hallo! I said hallo!";
                  > var yourRegExp_as_t ext="\\w{5}"; //that checks for 5 letters long words
                  > var regExpObject=ne w RegExp();
                  > //now use the built in method compile
                  > regExpObject.co mpile(yourRegEx p_as_text, "gi");
                  > /*the second argument takes in the so called modifiers. g stands fopr GLOBAL
                  > scope (search ALL the occurrencies, that is), i stands for case INsensitive
                  > search*/
                  >
                  > //Now you have a valid regular expression
                  > /*use it with methods that are regular expression methods, instance
                  > replace():*/
                  > test_string=tes t_string.replac e(regExpObject, "HI"); /*replaced hallo with
                  > HI*/
                  > alert(test_stri ng)
                  > //--></script>
                  >
                  > Once you don't need replacing, that's not a problem, you can use search:
                  > test_string.seR CH(regExpObject );
                  >
                  > You'd have to work a bit yourself on the codes sent as a reply.
                  > Anyway, to get closer to your needs:
                  >
                  > <script><!--
                  > var somestringarray = new Array( "one", "two", "three" );
                  > var somestring = "This is one of my favorite";
                  > var regExpObject=ne w RegExp();
                  > for( var i = 0; i < somestringarray .length; i++ )
                  > {
                  > regExpObject.co mpile(somestrin garray[i], "gi");
                  > if( somestring.matc h( regExpObject ))
                  > {alert(somestri ngarray[i])
                  > break;
                  > }
                  > }
                  > //--></script>
                  >
                  > ciao
                  > Alberto
                  > http://www.unitedscripters.com/[/color]

                  Comment

                  • Alberto

                    #10
                    Re: How to build a regular expression on runtime?

                    You're very welcome. Happy tho have been helpful.

                    ciao
                    Alberto



                    "Harry" <harald.humml @t-systems.at> ha scritto nel messaggio
                    news:b3271585.0 408180347.6642c 09a@posting.goo gle.com...[color=blue]
                    > Hi,
                    >
                    > Ok, I´ve it now. Thank you all for the helpful replies. Great forum!
                    >
                    > Harry
                    >
                    >
                    >
                    > "Alberto" <nospam@nospam. nospam> wrote in message[/color]
                    news:<FmqUc.148 822$5D1.7342145 @news4.tin.it>. ..[color=blue][color=green]
                    > > Hello
                    > >
                    > > it doesn't matter whether you want to replace or search: what you[/color][/color]
                    basically[color=blue][color=green]
                    > > need is to compile a regular expression on the run, ISN'T IT?
                    > > Try the code I sent to you:
                    > >
                    > > <script><!--
                    > > var test_string="ha llo guy hallo! I said hallo!";
                    > > var yourRegExp_as_t ext="\\w{5}"; //that checks for 5 letters long words
                    > > var regExpObject=ne w RegExp();
                    > > //now use the built in method compile
                    > > regExpObject.co mpile(yourRegEx p_as_text, "gi");
                    > > /*the second argument takes in the so called modifiers. g stands fopr[/color][/color]
                    GLOBAL[color=blue][color=green]
                    > > scope (search ALL the occurrencies, that is), i stands for case[/color][/color]
                    INsensitive[color=blue][color=green]
                    > > search*/
                    > >
                    > > //Now you have a valid regular expression
                    > > /*use it with methods that are regular expression methods, instance
                    > > replace():*/
                    > > test_string=tes t_string.replac e(regExpObject, "HI"); /*replaced hallo[/color][/color]
                    with[color=blue][color=green]
                    > > HI*/
                    > > alert(test_stri ng)
                    > > //--></script>
                    > >
                    > > Once you don't need replacing, that's not a problem, you can use search:
                    > > test_string.seR CH(regExpObject );
                    > >
                    > > You'd have to work a bit yourself on the codes sent as a reply.
                    > > Anyway, to get closer to your needs:
                    > >
                    > > <script><!--
                    > > var somestringarray = new Array( "one", "two", "three" );
                    > > var somestring = "This is one of my favorite";
                    > > var regExpObject=ne w RegExp();
                    > > for( var i = 0; i < somestringarray .length; i++ )
                    > > {
                    > > regExpObject.co mpile(somestrin garray[i], "gi");
                    > > if( somestring.matc h( regExpObject ))
                    > > {alert(somestri ngarray[i])
                    > > break;
                    > > }
                    > > }
                    > > //--></script>
                    > >
                    > > ciao
                    > > Alberto
                    > > http://www.unitedscripters.com/[/color][/color]


                    Comment

                    Working...