parti
parti

Reputation: 215

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: site.
Invalid input: -site. or site-.

Upvotes: 1

Views: 959

Answers (2)

anubhava
anubhava

Reputation: 784898

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 negative lookaheads for this:

/^(?!-|.*(\.[.-]|-\.|-$))(?:[A-Z0-9-]{0,62}\.){1,8}[A-Z0-9]{3}$/gim

RegEx Demo

Upvotes: 1

Juan Tomas
Juan Tomas

Reputation: 5183

Try:

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

I'm not 100% sure it will work with JS regexes. The idea is: ^ matches beginning of string, $ matches end, and ^- in a character class means "anything not a hyphen".

Upvotes: 0

Related Questions