DSharper
DSharper

Reputation: 3217

Regular expression to prevent adjacent repeating dashes

In my asp.net application I am restricting allowed URL formats with regular expressions.I need to create regular expression which will not allow adjacent dashes in URLs

01) allow URLs like

text1-text2.htm
text1-text2-textn.htm

02) prevent URLS like

text1--text2.htm
text1--text2-textn.htm

Upvotes: 0

Views: 2558

Answers (5)

Ray Toal
Ray Toal

Reputation: 88468

The negative answer posted by Aziz is best, but just for completeness sake here is a regex that matches the kinds of strings you wish to accept (as opposed to reject):

You want a string made up of zero or more of the following:

  • a non-dash character, or
  • a dash followed by a non-dash

A regex for this is

/^(?:[^-]|-(?!-))*$/

Now you can adjust the [^-] part to accept not just any character at all, but only those characters permitted in a URL (that is, if you wish to match all possible urls except those with two consecutive dashes). To do this you will have to find the RFC that gives the URI syntax. Will be somewhat tedious, which is why the negative solution with /--/ combined with other checks is your best bet.

Upvotes: 1

Brandon Montgomery
Brandon Montgomery

Reputation: 6986

url.Contains("--") will work for you, where the url variable is the url entered. Nice and concise, and you don't have to fuss with a RegEx.

Upvotes: 1

Mikulas Dite
Mikulas Dite

Reputation: 7941

Should be enough to search for the problem -{2,} and then do the negation. Ie as long as this regex (two or more dashes in a row) does not match, it's valid.

Or positive regex matching only urls you do want: ^([A-Za-z0-9]+-?)+\.htm$

Upvotes: 0

Cliff
Cliff

Reputation: 1701

This will match a filename with 0 or more occurences of a single dash followed by a some word characters.

^\w+(-\w+)*\.\w+

Upvotes: 0

Aziz Shaikh
Aziz Shaikh

Reputation: 16544

Try this regex:

/--/

If you found a match then it means the URL had two dashes.

Upvotes: 1

Related Questions