473,386 Members | 1,962 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

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:

"01234abcdef" 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.

Jul 23 '05 #1
14 2870
"enrique" <en************@gmail.com> writes:
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.
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 :)
Here it is: /\w+(-?\w+)*/
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+)*$/
Test cases that I expect to pass are failing: .... "0123-412-8370" false (should've been "true")
It is true for me. Show us some more code, and tell us which browser
you use.
"asdkfjakfj" true

"0-1" false (should've been "true")
Is true for me. What is the rest of your code, and what browser are
you using?
"-ABC123" false
Should be true for the provided regular expression (and is for me).

Try writing this in the address line:
javascript:alert(/\w+(-?\w+)*/.test("-ABC123"))
"00230-" false

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

"1-" false
Should all be true for the provided regexp.
Would anyone lend a hand?


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 - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #2
> 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 :)


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("01234abcdef", "0123-412-8370", "asdkfjakfj",
"0-1", "-", "--", "-ABC123", "00230-", "ABC-123", "1-", "111223333");
for (i = 0, j = tests.length; i < j; ++i)
{
document.writeln("<p>&quot;<strong>" + eval("tests[i]") +
"</strong>&quot; <em>" + eval("IsAccountNumber(tests[i])") +
"</em></p>");
}
</script>

Jul 23 '05 #3
"enrique" <en************@gmail.com> writes:
I've been testing with Firefox. .... Here's the test harness:

<script type="text/javascript"> function IsAccountNumber(strString)
{
var strValidChars = /\w+(-?\w+)*/;
return validateString(strString, strValidChars);
So this is where it happens ... except that we can't see the
validateString method :)
}
var tests = new Array("01234abcdef", "0123-412-8370", "asdkfjakfj",
"0-1", "-", "--", "-ABC123", "00230-", "ABC-123", "1-", "111223333");
for (i = 0, j = tests.length; i < j; ++i)
{ document.writeln("<p>&quot;<strong>" + eval("tests[i]") +
"</strong>&quot; <em>" + eval("IsAccountNumber(tests[i])") +
"</em></p>");


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.writeln("<p>&quot;<strong>" + tests[i] +
"</strong>&quot;<em>" + IsAccountNumber(tests[i]) +
"</em></p>");

Never use "eval" :)

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #4
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.

Jul 23 '05 #5
JRS: In article <11**********************@g43g2000cwa.googlegroups .com>
, dated Thu, 19 May 2005 09:12:59, seen in news:comp.lang.javascript,
enrique <en************@gmail.com> posted :
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+)*/

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

?
For proper quoting when using Google for News :-
Keith Thompson wrote in comp.lang.c, message ID
<ln************@nuthaus.mib.org> :-
If you want to post a followup via groups.google.com, 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.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #6
Fill me on the "eval" function and your discouraging its use, please.

Thanks again.

epp

Jul 23 '05 #7
enrique wrote on 20 mei 2005 in comp.lang.javascript:
Fill me on the "eval" function and your discouraging its use, please.


[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.javascript>

mind the wordwrap trap

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

Jul 23 '05 #8
JRS: In article <Xn*******************@194.109.133.242>, dated Fri, 20
May 2005 14:35:21, seen in news:comp.lang.javascript, Evertjan.
<ex**************@interxnl.net> posted :
enrique wrote on 20 mei 2005 in comp.lang.javascript:
Fill me on the "eval" function and your discouraging its use, please.


[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.javascript>

mind the wordwrap trap


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 .javascript>

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.javascript>
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.9144000000000001,
explanation obvious.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #9
On 20/05/2005 21:33, Dr John Stockton wrote:
JRS: In article <Xn*******************@194.109.133.242>, dated Fri, 20
May 2005 14:35:21, seen in news:comp.lang.javascript, Evertjan.
<ex**************@interxnl.net> posted :
[snip]
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.javascript>


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.
Jul 23 '05 #10
JRS: In article <A9******************@text.news.blueyonder.co.uk >,
dated Fri, 20 May 2005 23:12:32, seen in news:comp.lang.javascript,
Michael Winter <m.******@blueyonder.co.invalid> posted :
On 20/05/2005 21:33, Dr John Stockton wrote:
JRS: In article <Xn*******************@194.109.133.242>, dated Fri, 20
May 2005 14:35:21, seen in news:comp.lang.javascript, Evertjan.
<ex**************@interxnl.net> posted :


[snip]
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.javascript>


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.

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.bgColor='red'
interact? Introducing CSS

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

containing body { color:black; background:#FFFFCC }

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.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #11
On 21/05/2005 21:32, Dr John Stockton wrote:

[snip]
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?
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.demon.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.
Question : How should CSS and javascript document.bgColor='red'
interact? [...]


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.style.backgroundColor = 'red';

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #12
JRS: In article <1n******************@text.news.blueyonder.co.uk >,
dated Sun, 22 May 2005 14:07:57, seen in news:comp.lang.javascript,
Michael Winter <m.******@blueyonder.co.invalid> posted :
On 21/05/2005 21:32, Dr John Stockton wrote:

[snip]
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?
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.demon.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.


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.

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.


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.

Question : How should CSS and javascript document.bgColor='red'
interact? [...]


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.style.backgroundColor = 'red';


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.demon.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)
Jul 23 '05 #13
On 22/05/2005 21:50, Dr John Stockton wrote:
I don't support Netscape 4 on the site [...]
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]
I take it that you mean that TestBox.value should be
document.forms["xxx"].TestBox.value ?
That, or use an id with getElementById (and appropriate emulation for IE4).
[...] It's an error that MSIE does not see, so there are probably
still a few more like that lurking on other pages, alas.


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.
Jul 23 '05 #14
JRS: In article <79******************@text.news.blueyonder.co.uk >,
dated Sun, 22 May 2005 22:59:15, seen in news:comp.lang.javascript,
Michael Winter <m.******@blueyonder.co.invalid> posted :
On 22/05/2005 21:50, Dr John Stockton wrote:
I take it that you mean that TestBox.value should be
document.forms["xxx"].TestBox.value ?


That, or use an id with getElementById (and appropriate emulation for IE4).


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

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


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.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Joe | last post by:
Hi, I have been using a regular expression that I don’t uite understand to filter the valid email address. My regular expression is as follows: <asp:RegularExpressionValidator...
8
by: Bibe | last post by:
I've been trying to get this going for awhile now, and need help. I've done a regex object, and when I use IsMatch, it's behavior is quite weird. I am trying to use Regex to make sure that a...
3
by: Vidar Skjelanger | last post by:
I have a regex for matching VB6-functions, but it hangs on one specific function. The regex: ...
7
by: Razzie | last post by:
Hey all, Decided to give a shot at Regular expressions - need a bit of help :) I can't seem to find the right regex for matching words like "*test*" or *somevalue*" - in short, all words...
2
by: Tony Ciconte | last post by:
Does anyone know of or have any VBA code or similar logic that can help distinguish similar first/last name combinations? For example, we would like to prompt the user of a possible match when any...
15
by: nagar | last post by:
I need to split a string whenever a separator string is present (lets sey #Key(val) where val is a variable) and rejoin it in the proper order after doing some processing. Is there a way to use...
2
by: Mick Walker | last post by:
Hi All, I would like to know how I can limit users to only registering usernames which have alphanumberic characters and one underscore. From what I understand is I can use a regex to do this....
2
by: DotNetNewbie | last post by:
Hi, I want to replace all consecutive (2 or more) dashes into a single dash. So text like "hello--world is-cool------ok?" should become "hello-word is-cool-ok?" so it doesn't effect...
0
by: Itanium | last post by:
Hi all. I need to recognize some special keywords in my app. I usually accomplish this task with a regex construction like this… \bkeyword\b …that means “match the keyword if it is preceded...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.