Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex not start with dot or end with dot

Tags:

python

regex

I need a regular expression that does not start with a dot or end with [-_.].

This regex works but fails for the first condition; it does not start with dot:

^[A-Za-z0-9][^.]*[^-_.][A-Za-z0-9]$

For example: test.com should be a valid string but it fails.

like image 486
user1050619 Avatar asked Feb 04 '14 16:02

user1050619


People also ask

How do you escape a dot in regex?

(dot) metacharacter, and can match any single character (letter, digit, whitespace, everything). You may notice that this actually overrides the matching of the period character, so in order to specifically match a period, you need to escape the dot by using a slash \.

What does \b mean in regex?

The \b metacharacter matches at the beginning or end of a word.

What does \+ mean in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" .

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .


1 Answers

Using negative lookaheads to assert your requirements for the string:

^(?!^\.)(?!.*[-_.]$)[a-zA-Z0-9]+$
  • First character not a "."
  • Last character not a "-", "_", or "."
  • Also at least one character in length
like image 171
tenub Avatar answered Sep 20 '22 11:09

tenub