Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to disallow more than 1 dash consecutively

Tags:

regex

  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.

like image 259
cometta Avatar asked Feb 04 '11 11:02

cometta


People also ask

What does \+ mean in regex?

For examples, \+ matches "+" ; \[ matches "[" ; and \. matches "." . Regex also recognizes common escape sequences such as \n for newline, \t for tab, \r for carriage-return, \nnn for a up to 3-digit octal number, \xhh for a two-digit hex code, \uhhhh for a 4-digit Unicode, \uhhhhhhhh for a 8-digit Unicode.

What is regex multiline mode?

Multiline option, or the m inline option, enables the regular expression engine to handle an input string that consists of multiple lines. It changes the interpretation of the ^ and $ language elements so that they match the beginning and end of a line, instead of the beginning and end of the input string.

Do dashes need to be escaped 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). Save this answer.


1 Answers

^(?!-)(?!.*--)[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
like image 101
Tim Pietzcker Avatar answered Jan 11 '23 11:01

Tim Pietzcker