parti parti - 4 months ago 6
Javascript Question

No match in regex if character at beginning or end of string

I'm trying in regular expression to not match if '-' is at the end of a string.
Here's a partial of my regex (this is looking at domain part of url, which can't have symbols at beginning or end, but can have '-' in middle of string:

(([A-Z0-9])([A-Z0-9-]){0,61}([A-Z0-9]?)[\.]){1,8}


This also has to match 1-character domains - that's why I have ? on the end character & 0,61 on the center part.

So, in short is there a regex code to prevent matching for '-' if it's at the end of the string? And if you can prevent it for beginning, then that would be great too.

Matched input: www.site.com

Invalid input: www.-site.com or www.site-.com

Answer

in short is there a regex code to prevent matching for '-' if it's at the end of the string? And if you can prevent it for beginning, then that would be great too.

Yes you can use 2 negative lookaheads for this:

/^(?!-)(?!.*-$)/
  • ^(?!-) - will assert failure if - is at the beginning
  • (?!.*-$) - will assert failure if - is at the end

RegEx Demo

Comments