cometta
cometta

Reputation: 35679

Regex to disallow more than 1 dash consecutively

  1. How can I disallow -- (more than 1 consecutive -)? e.g. ab--c
  2. - at the back of words not allow, e.g. abc-
  3. - at start of words not allow, e.g. -abc

^[A-Za-z0-9-]+$ is what I have so far.

Upvotes: 24

Views: 18994

Answers (5)

Ubanantu
Ubanantu

Reputation: 19

Try: ^([a-zA-Z0-9]+[-]{1})*[a-zA-Z0-9]+$

Regex101 link: https://regex101.com/r/xZ2g6p/1

This allows only one hyphen inbetween two set of characters and blocks it at the beginning & at the end of the character set.

Upvotes: 1

Gaétan RYCKEBOER
Gaétan RYCKEBOER

Reputation: 304

If “-” is not allowed at the beginning nor end of the string, you are searching for a sequence of “one or more alanum, followed by one or more group(s) of one dash followed by 1 or more alanum”

/[0-9A-Z]+(-[0-9A-Z]+)+/

Simple is a valuable motto with regular expressions. (nota : to search small case characters, add them. I didn't for clarity)

Upvotes: 0

Kareem
Kareem

Reputation: 5404

^[a-zA-Z0-9](?!.*--)[a-zA-Z0-9-]*[a-zA-Z0-9]$

^[a-zA-Z0-9]     /*Starts with a letter or a number*/
(?!.*--)         /*Doesn't include 2 dashes in a row*/
[a-zA-Z0-9-]*    /*After first character, allow letters or numbers or dashes*/
[a-zA-Z0-9]$     /*Ends with a letter or a number*/

Matches:

Re-play / Re-play-ed

Doesn't Match:

Replay- / Re--Play / -Replay

Upvotes: 2

Brian Reichle
Brian Reichle

Reputation: 2856

^[A-Za-z0-9]+(-[A-Za-z0-9]+)*$

Using this regular expression, the hyphen is only matched just inside the group. This hyphen has the [A-Za-z0-9]+ sub-expression appearing on each side. Because this sub-expression matches on one or more alpha numeric characters, its not possible for a hyphen to match at the start, end or next to another hyphen.

Upvotes: 40

Tim Pietzcker
Tim Pietzcker

Reputation: 336078

^(?!-)(?!.*--)[A-Za-z0-9-]+(?<!-)$

Explanation:

^             # Anchor at start of string
(?!-)         # Assert that the first character isn't a -
(?!.*--)      # Assert that there are no -- present anywhere
[A-Za-z0-9-]+ # Match one or more allowed characters
(?<!-)        # Assert that the last one isn't a -
$             # Anchor at end of string

Upvotes: 44

Related Questions