Link to home
Start Free TrialLog in
Avatar of catonthecouchproductions
catonthecouchproductionsFlag for United States of America

asked on

Regex to match a dash

I have been digging through trying to get a reg ex to match "-" more detailed something like:

2324sA-D13

That format doesnt really matter, but at least if it allows a dash, any number of dashes? Any ideas?

Thanks.
Avatar of chrios
chrios
Flag of Sweden image

What language are you using?
Normally a dash does not need to be treated in any special way, so a pattern like "\w+-\w+" should work in that example. (Some dialects need the + to be escaped when used a s a multiplier.)

If that does not work, try adding a \ before -, like this: \w+\-\w+

Good luck.
Avatar of catonthecouchproductions

ASKER

I am working with JS
Avatar of Justin Mathews
Justin Mathews

If you are looking for something to match non-dash characaters followed by any number of  dash followed by non-dash characaters pattern use:

/[^\-]*(-[^\-]*)*/
In that case have a look at this page to test out your pattern:

http://www.regular-expressions.info/javascriptexample.html

\w+-\w+ matches your given pattern without grouping.
(\w+)-(\w+) Should work and place 2324sA and D13 in two groups that you can use.
Thank you! I think that is really close, what about add alpha num along with dashes?

Then i think we're good.

Ryan
SOLUTION
Avatar of Justin Mathews
Justin Mathews

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I tried regex tester and used: 5436345A-AA - As an example and didnt pass. Right format correct?
In the tester you should give it without // as:

[\dA-Za-z]*(-[\dA-Za-z]*)*
Ahh...thanks!
Sorry one last thing, is it possible to make it take only dashes and no: $ % ^ & * (  ! @, etc.

It worked great in the tester btw

Thanks
So is it the "-" in the middle of the two groups that specifys that it CAN allow dashes?
Yes. Currently it allows only alpha-nums and dashes.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@chrios, thank you for that.

Appreciate your help guys. Been dealing with alot of regex lately, starting to slowly but surely understand it. Still a bit intimidating, you guys seem like you have it down.

Thanks
Glad to help, good luck.