Regular Expression pattern

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

    Regular Expression pattern

    Greeting,

    I want to extract all "[XXX]" from a string, what pattern should I
    used?

    eg.
    [test1] = [test2]

    - return array [test1] or test1, [test2] or test2

    I tried \[(.*)\] , but it returned the whole "[test1] = [test2]"!

    Anyone can help? Also, got any good reference sites especially with
    rich example for this patterning?
  • Janwillem Borleffs

    #2
    Re: Regular Expression pattern


    "Kelmen Wong" <kelmen@hotmail .com> schreef in bericht
    news:843f541b.0 309082300.59afc 810@posting.goo gle.com...[color=blue]
    > Greeting,
    >
    > I want to extract all "[XXX]" from a string, what pattern should I
    > used?
    >[/color]

    var string = "[test1] = [test2]";
    var reg = /\[[^\]]+\]/g;
    var matches = string.match(re g);

    for (m in matches) alert(matches[m]);


    JW



    Comment

    • Lasse Reichstein Nielsen

      #3
      Re: Regular Expression pattern

      kelmen@hotmail. com (Kelmen Wong) writes:
      [color=blue]
      > I want to extract all "[XXX]" from a string, what pattern should I
      > used?[/color]

      You want to have a string, and then create an array of all strings in
      it that are delimitered by "[" and "]"?
      [color=blue]
      > eg.
      > [test1] = [test2]
      >
      > - return array [test1] or test1, [test2] or test2
      >
      > I tried \[(.*)\] , but it returned the whole "[test1] = [test2]"![/color]

      Yes, regular expressions try to match as much as possible.
      The trick is to not use "." between the two brackets, but [^\]], i.e.,
      matchin everything except an end bracket.

      Try
      function extractBrackete d(str) {
      var result = [];
      var re = /\[([^\]]*)\]/g ;
      var match;
      while ((match = re.exec(str))) {
      result.push(mat ch[1]);
      }
      return result;
      }

      /L
      --
      Lasse Reichstein Nielsen - lrn@hotpop.com
      Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit. html>
      'Faith without judgement merely degrades the spirit divine.'

      Comment

      • peter seliger

        #4
        Re: Regular Expression pattern

        kelmen@hotmail. com (Kelmen Wong) wrote in message news:<843f541b. 0309082300.59af c810@posting.go ogle.com>...

        <html>

        <head>
        <title>none-greedy RegExp-pattern</title>
        <script type="text/javascript">
        <!--
        /*
        hi Kelmen,

        [color=blue]
        > eg.
        > [test1] = [test2]
        >
        > - return array [test1] or test1, [test2] or test2
        >
        > I tried \[(.*)\] , but it returned the whole "[test1] = [test2]"![/color]

        thats due to the greedy nature of RegExp-patterns;

        and "greedy" means:
        a pattern alway tries to take as much chracters of
        a given string as long as the search rule will match;

        in your example "[test1] = [test2]" the last possible
        character that will fit with the RegExp /\[(.*)\]/;
        is the closing square-bracket of "...test2]" because
        of ".*" that allowes as much characters as possible
        between an opening and a closing square-bracket;

        none-greedy patterns will solve your problem;

        you might play with the following lines:
        */

        var givenString = "test1 [test2] test3] [test4] [test5] [test6
        [test7 test8]";
        var regExpression = /\[[^\]]*\]/g;
        // look for a opening square bracket - \[ -
        // then for everything that is not a closing square bracket -
        [^\]] - as often as you can - * -
        // till you find a closing square bracket - \] -
        // and use this pattern for the entire string - g -
        var matches = [];

        if (regExpression. test(givenStrin g)) {
        matches = givenString.mat ch(regExpressio n);
        }
        alert("matches. length = " + matches.length +
        "\nmatches.join (\"\\n\") :\n" + matches.join("\ n"));


        regExpression = /\[[^\[\]]*\]/g;
        // look for a opening square bracket - \[ -
        // then for everything that is neither a opening nor a closing
        square bracket - [^\[\]] - as often as you can - * -
        // till you find a closing square bracket - \] -
        // and use this pattern for the entire string - g -
        if (regExpression. test(givenStrin g)) {
        matches = givenString.mat ch(regExpressio n);
        }
        alert("matches. length = " + matches.length +
        "\nmatches.join (\"\\n\") :\n" + matches.join("\ n"));

        givenString = "[test1] = [test2]";
        if (regExpression. test(givenStrin g)) {
        matches = givenString.mat ch(regExpressio n);
        }
        alert("matches. length = " + matches.length +
        "\nmatches.join (\"\\n\") :\n" + matches.join("\ n"));

        // if you like to free your matches from its enclosing brackets
        treat your "matches"-array as shown right now:
        //
        // matches = matches.join("s plitnjoin");ale rt(matches);
        // matches = matches.replace (/\[/g,"");alert(mat ches);
        // matches = matches.replace (/\]/g,"");alert(mat ches);
        // matches = matches.split(" splitnjoin");al ert(matches);
        //
        matches = matches.join("s plitnjoin").rep lace(/\[/g,"").replace (/\]/g,"").split("sp litnjoin");

        alert("free from enclosing brackets\n\nmat ches.join(\"\\n \") :\n"
        + matches.join("\ n"));

        // NOTE:
        //
        // in javascript 1.5 none-greedy search patterns can easly
        // be written by using the punctuation character "?";
        //
        // /\[[^\]]*\]/g; then will be /\[.*?\]/g;

        /*
        givenString = "test1 [test2] test3] [test4] [test5] [test6 [test7
        test8]";
        regExpression = /\[.*?\]/g; // was: /\[[^\]]*\]/g;

        if (regExpression. test(givenStrin g)) {
        matches = givenString.mat ch(regExpressio n);
        }
        alert("matches. length = " + matches.length +
        "\nmatches.join (\"\\n\") :\n" + matches.join("\ n"));


        // /\[[^\[\]]*\]/g; will turn into /\[[^\[]*?\]/g;

        regExpression = /\[[^\[]*?\]/g; // was: /\[[^\[\]]*\]/g;

        if (regExpression. test(givenStrin g)) {
        matches = givenString.mat ch(regExpressio n);
        }
        alert("matches. length = " + matches.length +
        "\nmatches.join (\"\\n\") :\n" + matches.join("\ n"));
        */

        //
        // have fun - regards - peterS. - pseliger@gmx.ne t
        //

        //-->
        </script>
        <head>

        <body>
        </body>

        </html>

        Comment

        • Lasse Reichstein Nielsen

          #5
          Re: Regular Expression pattern

          pseliger@gmx.ne t (peter seliger) writes:
          [color=blue]
          > thats due to the greedy nature of RegExp-patterns;
          >
          > and "greedy" means:
          > a pattern alway tries to take as much chracters of
          > a given string as long as the search rule will match;[/color]

          In modern implementations of Javscrip (i.e., ECMAScript) you can
          use a non-greedy * or + operator (like you can in Perl).

          The regular expression is then:

          /\[.*?\]/

          It finds a "[" followed by the shortest possible match of any characters,
          followed by a "]".

          It doesn't work in, e.g., Netscape 4.
          /L
          --
          Lasse Reichstein Nielsen - lrn@hotpop.com
          Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit. html>
          'Faith without judgement merely degrades the spirit divine.'

          Comment

          • peter seliger

            #6
            Re: Regular Expression pattern

            kelmen@hotmail. com (Kelmen Wong) wrote in message news:<843f541b. 0309082300.59af c810@posting.go ogle.com>...


            <html>

            <head>
            <title>none-greedy RegExp-pattern</title>
            <script type="text/javascript">
            <!--
            /*
            hi Kelmen,

            [color=blue]
            > eg.
            > [test1] = [test2]
            >
            > - return array [test1] or test1, [test2] or test2
            >
            > I tried \[(.*)\] , but it returned the whole "[test1] = [test2]"![/color]

            thats due to the greedy nature of RegExp-patterns;

            and "greedy" means:
            a pattern alway tries to take as much chracters of
            a given string as long as the search rule will match;

            in your example "[test1] = [test2]" the last possible
            character that will fit with the RegExp /\[(.*)\]/;
            is the closing square-bracket of "...test2]" because
            of ".*" that allowes as much characters as possible
            between an opening and a closing square-bracket;

            none-greedy patterns will solve your problem;

            you might play with the following lines:
            */

            var givenString = "test1 [test2] test3] [test4] [test5] [test6
            [test7 test8]";
            var regExpression = /\[[^\]]*\]/g;
            // look for a opening square bracket - \[ -
            // then for everything that is not a closing square bracket -
            [^\]] - as often as you can - * -
            // till you find a closing square bracket - \] -
            // and use this pattern for the entire string - g -
            var matches = [];

            if (regExpression. test(givenStrin g)) {
            matches = givenString.mat ch(regExpressio n);
            }
            alert("matches. length = " + matches.length +
            "\nmatches.join (\"\\n\") :\n" + matches.join("\ n"));


            regExpression = /\[[^\[\]]*\]/g;
            // look for a opening square bracket - \[ -
            // then for everything that is neither a opening nor a closing
            square bracket - [^\[\]] - as often as you can - * -
            // till you find a closing square bracket - \] -
            // and use this pattern for the entire string - g -
            if (regExpression. test(givenStrin g)) {
            matches = givenString.mat ch(regExpressio n);
            }
            alert("matches. length = " + matches.length +
            "\nmatches.join (\"\\n\") :\n" + matches.join("\ n"));

            givenString = "[test1] = [test2]";
            if (regExpression. test(givenStrin g)) {
            matches = givenString.mat ch(regExpressio n);
            }
            alert("matches. length = " + matches.length +
            "\nmatches.join (\"\\n\") :\n" + matches.join("\ n"));

            // if you like to free your matches from its enclosing brackets
            treat your "matches"-array as shown right now:
            //
            // matches = matches.join("s plitnjoin");ale rt(matches);
            // matches = matches.replace (/\[/g,"");alert(mat ches);
            // matches = matches.replace (/\]/g,"");alert(mat ches);
            // matches = matches.split(" splitnjoin");al ert(matches);
            //
            matches = matches.join("s plitnjoin").rep lace(/\[/g,"").replace (/\]/g,"").split("sp litnjoin");

            alert("free from enclosing brackets\n\nmat ches.join(\"\\n \") :\n"
            + matches.join("\ n"));

            // NOTE:
            //
            // in javascript 1.5 none-greedy search patterns can easly
            // be written by using the punctuation character "?";
            //
            // /\[[^\]]*\]/g; then will be /\[.*?\]/g;

            /*
            givenString = "test1 [test2] test3] [test4] [test5] [test6 [test7
            test8]";
            regExpression = /\[.*?\]/g; // was: /\[[^\]]*\]/g;

            if (regExpression. test(givenStrin g)) {
            matches = givenString.mat ch(regExpressio n);
            }
            alert("matches. length = " + matches.length +
            "\nmatches.join (\"\\n\") :\n" + matches.join("\ n"));


            // /\[[^\[\]]*\]/g; will turn into /\[[^\[]*?\]/g;

            regExpression = /\[[^\[]*?\]/g; // was: /\[[^\[\]]*\]/g;

            if (regExpression. test(givenStrin g)) {
            matches = givenString.mat ch(regExpressio n);
            }
            alert("matches. length = " + matches.length +
            "\nmatches.join (\"\\n\") :\n" + matches.join("\ n"));
            */

            //
            // have fun - regards - peterS. - pseliger@gmx.ne t
            //

            //-->
            </script>
            <head>

            <body>
            </body>

            </html>

            Comment

            Working...