regex help: alphanumeric with optional dashes

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

    regex help: alphanumeric with optional dashes

    I'm trying to debug my expression that matches an alphanumeric with any
    number of dashes (including none), except at the ends and obviously
    disallowing two or more consecutive dashes.

    Here it is: /\w+(-?\w+)*/

    Test cases that I expect to pass are failing:

    "01234abcde f" true

    "0123-412-8370" false (should've been "true")

    "asdkfjakfj " true

    "0-1" false (should've been "true")

    "-" false

    "--" false

    "-ABC123" false

    "00230-" false

    "ABC-123" false (should've been "true")

    "1-" false

    "111223333" true

    Would anyone lend a hand? Thank you.

  • Lasse Reichstein Nielsen

    #2
    Re: regex help: alphanumeric with optional dashes

    "enrique" <enrique.pineda @gmail.com> writes:
    [color=blue]
    > I'm trying to debug my expression that matches an alphanumeric with any
    > number of dashes (including none), except at the ends and obviously
    > disallowing two or more consecutive dashes.[/color]

    Didn't I see you in the Java group. Even deleted my answer because I
    answer as if it was a Javascript question. I feel ... vindicated :)
    [color=blue]
    > Here it is: /\w+(-?\w+)*/[/color]

    It should match the examples you give. Actually, it matches and
    string with a word character in it, so it should probably be anchored.
    Also, the "?" isn't necessary. So, try this:

    /^\w+(-\w+)*$/
    [color=blue]
    > Test cases that I expect to pass are failing:[/color]
    ....[color=blue]
    > "0123-412-8370" false (should've been "true")[/color]

    It is true for me. Show us some more code, and tell us which browser
    you use.
    [color=blue]
    > "asdkfjakfj " true
    >
    > "0-1" false (should've been "true")[/color]

    Is true for me. What is the rest of your code, and what browser are
    you using?
    [color=blue]
    > "-ABC123" false[/color]

    Should be true for the provided regular expression (and is for me).

    Try writing this in the address line:
    javascript:aler t(/\w+(-?\w+)*/.test("-ABC123"))
    [color=blue]
    > "00230-" false
    >
    > "ABC-123" false (should've been "true")
    >
    > "1-" false[/color]

    Should all be true for the provided regexp.
    [color=blue]
    > Would anyone lend a hand?[/color]

    You are doing something wrong. It's impossible to say what, since you
    haven't told us what you do :) The regular expression, while not perfect,
    should not give the results you report, and doesn't in my browsers.

    /L
    --
    Lasse Reichstein Nielsen - lrn@hotpop.com
    DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
    'Faith without judgement merely degrades the spirit divine.'

    Comment

    • enrique

      #3
      Re: regex help: alphanumeric with optional dashes

      > Didn't I see you in the Java group. Even deleted my answer because I[color=blue]
      > answer as if it was a Javascript question. I feel ... vindicated :)[/color]

      Yup, I'm busted. I'm such a dope; wrong usenet group. I think I can
      safely un-post from the other group now that you have taken you reply
      out.

      I've been testing with Firefox. I've been storing test cases in an
      array, and then iterating over this collection and calling a validation
      method that makes use of the expression above. Here's the test
      harness:

      <script type="text/javascript">
      function IsAccountNumber (strString)
      {
      var strValidChars = /\w+(-?\w+)*/;
      return validateString( strString, strValidChars);
      }
      var tests = new Array("01234abc def", "0123-412-8370", "asdkfjakfj ",
      "0-1", "-", "--", "-ABC123", "00230-", "ABC-123", "1-", "111223333" );
      for (i = 0, j = tests.length; i < j; ++i)
      {
      document.writel n("<p>&quot;<st rong>" + eval("tests[i]") +
      "</strong>&quot; <em>" + eval("IsAccount Number(tests[i])") +
      "</em></p>");
      }
      </script>

      Comment

      • Lasse Reichstein Nielsen

        #4
        Re: regex help: alphanumeric with optional dashes

        "enrique" <enrique.pineda @gmail.com> writes:
        [color=blue]
        > I've been testing with Firefox.[/color]
        ....[color=blue]
        > Here's the test harness:
        >
        > <script type="text/javascript">[/color]
        [color=blue]
        > function IsAccountNumber (strString)
        > {
        > var strValidChars = /\w+(-?\w+)*/;
        > return validateString( strString, strValidChars);[/color]

        So this is where it happens ... except that we can't see the
        validateString method :)
        [color=blue]
        > }
        > var tests = new Array("01234abc def", "0123-412-8370", "asdkfjakfj ",
        > "0-1", "-", "--", "-ABC123", "00230-", "ABC-123", "1-", "111223333" );
        > for (i = 0, j = tests.length; i < j; ++i)
        > {[/color]
        [color=blue]
        > document.writel n("<p>&quot;<st rong>" + eval("tests[i]") +
        > "</strong>&quot; <em>" + eval("IsAccount Number(tests[i])") +
        > "</em></p>");[/color]

        Overuse of eval, but otherwise I can't see a problem with this. This
        works just the same, and doesn't reparse the string on every pass
        through the loop:

        document.writel n("<p>&quot;<st rong>" + tests[i] +
        "</strong>&quot;<e m>" + IsAccountNumber (tests[i]) +
        "</em></p>");

        Never use "eval" :)

        /L
        --
        Lasse Reichstein Nielsen - lrn@hotpop.com
        DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
        'Faith without judgement merely degrades the spirit divine.'

        Comment

        • enrique

          #5
          Re: regex help: alphanumeric with optional dashes

          Gosh, I'm a dope! The trouble is not even occurring in my regex; it's
          happening in my definition of "validateString ".

          Thanks very much for confirming the expression with your own testing.

          Comment

          • Dr John Stockton

            #6
            Re: regex help: alphanumeric with optional dashes

            JRS: In article <1116519179.858 023.320840@g43g 2000cwa.googleg roups.com>
            , dated Thu, 19 May 2005 09:12:59, seen in news:comp.lang. javascript,
            enrique <enrique.pineda @gmail.com> posted :[color=blue]
            >I'm trying to debug my expression that matches an alphanumeric with any
            >number of dashes (including none), except at the ends and obviously
            >disallowing two or more consecutive dashes.
            >
            >Here it is: /\w+(-?\w+)*/[/color]


            /^\w+(-\w+)*$/

            ?


            For proper quoting when using Google for News :-
            Keith Thompson wrote in comp.lang.c, message ID
            <lnwtuhfy7d.fsf @nuthaus.mib.or g> :-
            If you want to post a followup via groups.google.c om, don't use
            the "Reply" link at the bottom of the article. Click on "show options"
            at the top of the article, then click on the "Reply" at the bottom of
            the article headers.

            --
            © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
            <URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
            <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
            <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

            Comment

            • enrique

              #7
              Re: regex help: alphanumeric with optional dashes

              Fill me on the "eval" function and your discouraging its use, please.

              Thanks again.

              epp

              Comment

              • Evertjan.

                #8
                Re: regex help: alphanumeric with optional dashes

                enrique wrote on 20 mei 2005 in comp.lang.javas cript:[color=blue]
                > Fill me on the "eval" function and your discouraging its use, please.[/color]

                [Please quote, this is not email, but usenet. Thousands of users are
                reading too.]

                The archive of this NG has it all:

                <http://groups-beta.google.com/groups?num=100
                &q=eval.is.evil &as_ugroup=comp .lang.javascrip t>

                mind the wordwrap trap

                --
                Evertjan.
                The Netherlands.
                (Replace all crosses with dots in my emailaddress)

                Comment

                • Dr John Stockton

                  #9
                  Re: regex help: alphanumeric with optional dashes

                  JRS: In article <Xns965CA8C73B7 0eejj99@194.109 .133.242>, dated Fri, 20
                  May 2005 14:35:21, seen in news:comp.lang. javascript, Evertjan.
                  <exjxw.hannivoo rt@interxnl.net > posted :[color=blue]
                  >enrique wrote on 20 mei 2005 in comp.lang.javas cript:[color=green]
                  >> Fill me on the "eval" function and your discouraging its use, please.[/color]
                  >
                  >[Please quote, this is not email, but usenet. Thousands of users are
                  >reading too.]
                  >
                  >The archive of this NG has it all:
                  >
                  ><http://groups-beta.google.com/groups?num=100
                  >&q=eval.is.evi l&as_ugroup=com p.lang.javascri pt>
                  >
                  >mind the wordwrap trap[/color]

                  Good News software can post - and display - it without wrapping :

                  <http://groups-beta.google.com/groups?num=100> &q=eval.is.evil &as_ugroup=comp .lang.javascrip t>

                  The following should be understood as a unit be any reasonable
                  newsreader :-

                  <URL:http://groups-beta.google.com/groups?num=100>
                  &q=eval.is.evil &as_ugroup=comp .lang.javascrip t>


                  Please don't assume that everyone is reading News on-line; for off-line
                  readers a reference to the FAQ (which an off-line newsreader should
                  hold) is more helpful. You could even include a reference in your Sig.

                  No doubt Google has it all; but a lot of what it has is not worth
                  reading.

                  Function eval can be useful with form input :

                  var k = eval(<form-element>.value)

                  allows the Americans to enter distances correctly by typing the
                  distance in feet followed by *0.3048 .

                  Well, nearly correctly : eval("3*0.3048" ) -> 0.9144000000000 001,
                  explanation obvious.

                  --
                  © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
                  <URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
                  <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
                  <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

                  Comment

                  • Michael Winter

                    #10
                    Re: regex help: alphanumeric with optional dashes

                    On 20/05/2005 21:33, Dr John Stockton wrote:
                    [color=blue]
                    > JRS: In article <Xns965CA8C73B7 0eejj99@194.109 .133.242>, dated Fri, 20
                    > May 2005 14:35:21, seen in news:comp.lang. javascript, Evertjan.
                    > <exjxw.hannivoo rt@interxnl.net > posted :[/color]

                    [snip]
                    [color=blue]
                    > The following should be understood as a unit be any reasonable
                    > newsreader :-
                    >
                    > <URL:http://groups-beta.google.com/groups?num=100>
                    > &q=eval.is.evil &as_ugroup=comp .lang.javascrip t>[/color]

                    That would be true, if you pressed Delete once more - the extra bracket
                    has spoilt your demonstration. :) The same is true of the other URL.

                    [snip]

                    Mike

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

                    Comment

                    • Dr John Stockton

                      #11
                      Re: regex help: alphanumeric with optional dashes

                      JRS: In article <A9uje.36382$G8 .30383@text.new s.blueyonder.co .uk>,
                      dated Fri, 20 May 2005 23:12:32, seen in news:comp.lang. javascript,
                      Michael Winter <m.winter@bluey onder.co.invali d> posted :[color=blue]
                      >On 20/05/2005 21:33, Dr John Stockton wrote:
                      >[color=green]
                      >> JRS: In article <Xns965CA8C73B7 0eejj99@194.109 .133.242>, dated Fri, 20
                      >> May 2005 14:35:21, seen in news:comp.lang. javascript, Evertjan.
                      >> <exjxw.hannivoo rt@interxnl.net > posted :[/color]
                      >
                      >[snip]
                      >[color=green]
                      >> The following should be understood as a unit be any reasonable
                      >> newsreader :-
                      >>
                      >> <URL:http://groups-beta.google.com/groups?num=100>
                      >> &q=eval.is.evil &as_ugroup=comp .lang.javascrip t>[/color]
                      >
                      >That would be true, if you pressed Delete once more - the extra bracket
                      >has spoilt your demonstration. :) The same is true of the other URL.[/color]


                      Agreed, thanks. It was not possible for me to those lines that in the
                      article-being-edited.



                      I've introduced the improved code display and also CSS throughout my
                      site now; would some of you like to look at a few pages to see whether
                      they work for systems unlike mine?



                      Question : How should CSS and javascript document.bgColo r='red'
                      interact? Introducing CSS

                      <link rel="StyleSheet " href="styles-a.css" type="text/css">

                      containing body { color:black; background:#FFF FCC }

                      stops it working in my IE4, since the timed change of background colour
                      is fundamental and does not occur.

                      --
                      © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
                      <URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
                      <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
                      <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

                      Comment

                      • Michael Winter

                        #12
                        Re: regex help: alphanumeric with optional dashes

                        On 21/05/2005 21:32, Dr John Stockton wrote:

                        [snip]
                        [color=blue]
                        > I've introduced the improved code display and also CSS throughout my
                        > site now; would some of you like to look at a few pages to see whether
                        > they work for systems unlike mine?[/color]

                        There don't seem to be any immediate issues. If there are, I imagine
                        them to be limited to older user agents, and differences would be
                        relatively insignificant.

                        That said, I opened <URL:http://www.merlyn.demo n.co.uk/js-randm.htm> in
                        NN 4.77 and, after receiving messages about missing includes, the
                        instance promptly closed without any messages. I didn't see any close
                        method calls in the vicinity.

                        Staying with that particular document, you have a name-only reference to
                        'TestBox' in the speed tests section. Gecko-based user agents don't like
                        that very much.
                        [color=blue]
                        > Question : How should CSS and javascript document.bgColo r='red'
                        > interact? [...][/color]

                        I'd imagine, not very well. The usual way to override a style sheet
                        setting is through the style object of an element as that is considered
                        the highest form of specificity. You would be better off with

                        document.body.s tyle.background Color = 'red';

                        Mike

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

                        Comment

                        • Dr John Stockton

                          #13
                          Re: regex help: alphanumeric with optional dashes

                          JRS: In article <1n0ke.37137$G8 .11802@text.new s.blueyonder.co .uk>,
                          dated Sun, 22 May 2005 14:07:57, seen in news:comp.lang. javascript,
                          Michael Winter <m.winter@bluey onder.co.invali d> posted :[color=blue]
                          >On 21/05/2005 21:32, Dr John Stockton wrote:
                          >
                          >[snip]
                          >[color=green]
                          >> I've introduced the improved code display and also CSS throughout my
                          >> site now; would some of you like to look at a few pages to see whether
                          >> they work for systems unlike mine?[/color]
                          >
                          >There don't seem to be any immediate issues. If there are, I imagine
                          >them to be limited to older user agents, and differences would be
                          >relatively insignificant.
                          >
                          >That said, I opened <URL:http://www.merlyn.demo n.co.uk/js-randm.htm> in
                          >NN 4.77 and, after receiving messages about missing includes, the
                          >instance promptly closed without any messages. I didn't see any close
                          >method calls in the vicinity.[/color]

                          I don't close it intentionally. When I try without the include file,
                          there's no javascript running, it complains every time I call a function
                          from the include files during page load, and none of the buttons work -
                          which is not surprising.

                          I don't support Netscape 4 on the site, because I never had DynWrite
                          working in it, and I have no access to N4 anyway now. But that page
                          does not use DynWrite.

                          [color=blue]
                          >Staying with that particular document, you have a name-only reference to
                          >'TestBox' in the speed tests section. Gecko-based user agents don't like
                          >that very much.[/color]

                          I take it that you mean that TestBox.value should be
                          document.forms["xxx"].TestBox.value ? I've dealt with that, for
                          TestBox and its friends. It's an error that MSIE does not see, so there
                          are probably still a few more like that lurking on other pages, alas.

                          [color=blue][color=green]
                          >> Question : How should CSS and javascript document.bgColo r='red'
                          >> interact? [...][/color]
                          >
                          >I'd imagine, not very well. The usual way to override a style sheet
                          >setting is through the style object of an element as that is considered
                          >the highest form of specificity. You would be better off with
                          >
                          > document.body.s tyle.background Color = 'red';[/color]

                          Indeed I am, thanks; js-alarm.htm is the last of the more-or-less normal
                          pages to be CSS-upgraded, I think.

                          --
                          © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 MIME. ©
                          Web <URL:http://www.merlyn.demo n.co.uk/> - FAQish topics, acronyms, & links.
                          Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
                          Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)

                          Comment

                          • Michael Winter

                            #14
                            Re: regex help: alphanumeric with optional dashes

                            On 22/05/2005 21:50, Dr John Stockton wrote:
                            [color=blue]
                            > I don't support Netscape 4 on the site [...][/color]

                            And I don't necessarily suggest you do. I just took a look as NN4 can
                            react badly to some style sheet content. However, I'm pretty certain
                            that the closure isn't caused by the style sheet as it's too simple.

                            [snip]
                            [color=blue]
                            > I take it that you mean that TestBox.value should be
                            > document.forms["xxx"].TestBox.value ?[/color]

                            That, or use an id with getElementById (and appropriate emulation for IE4).
                            [color=blue]
                            > [...] It's an error that MSIE does not see, so there are probably
                            > still a few more like that lurking on other pages, alas.[/color]

                            I think I've mentioned occurrences whenever I've noticed them.

                            Whilst I remember: LEGEND elements (even empty ones) are required within
                            FIELDSET elements, and they must be the first non-whitespace content.

                            Mike

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

                            Comment

                            • Dr John Stockton

                              #15
                              Re: regex help: alphanumeric with optional dashes

                              JRS: In article <798ke.37518$G8 .26566@text.new s.blueyonder.co .uk>,
                              dated Sun, 22 May 2005 22:59:15, seen in news:comp.lang. javascript,
                              Michael Winter <m.winter@bluey onder.co.invali d> posted :[color=blue]
                              >On 22/05/2005 21:50, Dr John Stockton wrote:[/color]
                              [color=blue][color=green]
                              >> I take it that you mean that TestBox.value should be
                              >> document.forms["xxx"].TestBox.value ?[/color]
                              >
                              >That, or use an id with getElementById (and appropriate emulation for IE4).[/color]

                              DF = document.forms["xxx"]
                              ....
                              with (DF) { ... }
                              seems the best fix; I name my elements so that "with" ambiguities are
                              unlikely.

                              [color=blue]
                              >Whilst I remember: LEGEND elements (even empty ones) are required within
                              >FIELDSET elements, and they must be the first non-whitespace content.[/color]

                              Thanks. Now fixed in all the footers in the master, by substituting DIV
                              and adjusting TOE. I won't upload that change specifically, presuming
                              that the error was of little or no effect. I may change the style TOE
                              some more, as I don't like the result in IE4 (I suspect a bug). Short
                              changed page dm034-24.htm will be uploaded tonight, though; as will the
                              three pages which had that flaw in their "meat".

                              --
                              © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
                              <URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
                              <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
                              <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

                              Comment

                              Working...