473,804 Members | 3,272 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.

Jul 23 '05 #1
14 2925
"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:aler t(/\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/rasterTriangleD OM.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("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>

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("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>");


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 - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.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************ **********@g43g 2000cwa.googleg roups.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.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.
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.javas cript:
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.javascrip t>

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.javas cript:
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.evi l&as_ugroup=com p.lang.javascri pt>

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.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.
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.javascrip t>


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

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

Similar topics

2
1814
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 id="valValidEmail" runat="server" ControlToValidate="txtEmail" ValidationExpression="^(+)(\.+)*@(+)(\.+)*(\.{2,4})$"
8
5602
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 variable is only alphanumeric (no strange characters). Here's the code: Regex regExp = new Regex("*");
3
2706
by: Vidar Skjelanger | last post by:
I have a regex for matching VB6-functions, but it hangs on one specific function. The regex: ^(Public\s)?(Declare\s|Static\s)?(Function)\s(\S)+\(((Optional\s)?(ByVal\s|ByRef\s)?(ParamArray\s)?(\S)+(\sAs\s(\S)+)?(\s=\s(\S)+)?(\,\s)?)*\)(\sAs\s(\S)+)? The string on which it hangs: "Public Function FlaggAsOccupiedEx2(Pid As Long, UserName As String, Workstation As String, Optional IsReadOnly As Boolean = False,
7
1917
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 starting and ending with a *. I tried things like string regex = @"(^*\|*^)"); but it still doesn't work completely (matches on "*test" too for example). If anything could help me with this, that would be appreciated.
2
2528
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 of the first/last names Robert Smith, or Bob Smith, or Robt. Smith are used during data entry. All that is necessary is to alert the user so that they can review any appropriate existing records. We have done several google searches without any...
15
6005
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 the Regex.Split function to split the string whenever the #Key(val) occurrs but that keeps the #Key(val) occurrences to that I can reconstruct the final string after doing certain operations on each token (I need to basically convert each string...
2
1568
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. But I have no idea how to do it. I have only used a customfieldvalidor before. And the reason I cant do it now is because of the design of the page itself. So basically I need to know how, upon a button click, I can compare the text entered in a...
2
5236
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 anything except replace all consecutive dashes
0
1017
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 and succeeded by a non-alphanumeric character only”. This time I need to NOT allow a keyword to be matched if it is preceded or succeeded by a $ character, but unfortunately the damned regex engine considers the $ a non-alphanumeric character, so...
0
9708
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10340
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10327
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10085
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7625
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6857
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5527
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3828
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2999
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.