Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Regex, match any string with at least one hyphen

Tags:

regex

I'm a bit puzzled with a particular regex that is seemingly simple.

The match must be a string with only a-z, A-Z, 0-9 and must have at least one occurence of the '-' character anywhere in the string.

I have [a-zA-Z0-9-]+ but the problem is, it will also match those without the '-' character.

ABC123-ABC //should match

ABC123ABC //shouldn't match.
like image 373
maxp Avatar asked Jul 19 '11 08:07

maxp


People also ask

How do you match a hyphen in regex?

In regular expressions, the hyphen ("-") notation has special meaning; it indicates a range that would match any number from 0 to 9. As a result, you must escape the "-" character with a forward slash ("\") when matching the literal hyphens in a social security number.

Do we need to escape hyphen in regex?

You only need to escape the dash character if it could otherwise be interpreted as a range indicator (which can be the case inside a character class).

What is a dash in regex?

The dash - is a meta character if not in the beginning or at the end of a character class, e.g. [0-9] will match any digits between 0 and 9. If you only want to match 0, dash or 9, you need to escape the dash: [0\-9]


1 Answers

This should work:

^([a-zA-Z0-9]*-[a-zA-Z0-9]*)+$

Also if you want to have exactly 135 hyphens:

^([a-zA-Z0-9]*-[a-zA-Z0-9]*){135}$

or if you want to have at least 23 hyphens but not more than 54 hyphens:

^([a-zA-Z0-9]*-[a-zA-Z0-9]*){23,54}$

You get the point :)

like image 190
Petar Ivanov Avatar answered Sep 28 '22 11:09

Petar Ivanov