views:

342

answers:

2

I have a web application that takes input from a user, usually in the form of a filepath, hyperlink, or fileshare, but not always. A user may enter "\my.fileshare.com", "http://www.msdn.com", or "In my file cabinent". These inputs are exported to a Excel file. However, if the input is in the form of "\look on my desk" or "http://here it is" (notice the spaces), after the file is exported, and opened, Excel raises the ever so descriptive error message of, and I quote, "Error".

I'm adding to the existing code a regular expression validator to the textbox the user enters and edits these locations in. Because there are a large number of existing entries, the validator needs to be specific as possible, and only toss out the inputs that cause the Excel export to break. For example "\Will Work" will work, as will "Will Work", and "\This\will also work". I need a regular expression that if the string starts with \, http://, https://, ftp://, ftps://, the server or fileshare name does not have a space in it, and if it does not start with the \, http://, https://, ftp://, ftps://, its fine regardless.

I've been able to write the first part ^(\\)[^ \]+(\.)$|^(((ht|f)tp(s)?)\:\/\/)[^ \/]+(\/.)$

but I can't figure out how to say ignore everything if it does not start with \, http://, https://, ftp://, ftps://.

+1  A: 
 ^(?:(?:\\|(?:ht|f)tps?://)\S+|(?!\\|(?:ht|f)tps?://).*)$

Explained:

^                                 # start-of string
  (?:                             # begin non-capturing group
    (?:\\|(?:ht|f)tps?://)\S+     # "\, http, ftp" followed by non-spaces
    |                             # or
    (?!\\|(?:ht|f)tps?://).*      # NOT "\, http, ftp" followed by anything
  )                               # end non-capturing group
$                                 # end-of-string

This is pure, unescaped regex. Add character escaping according to the rules of your environment.

Tomalak
A: 

EDIT: Ooops premature.

This expression still doesn't allow "http://www.google.com/hello world" :/

EDIT FOR A THIRD TIME

Here we go!

^(?:(?:\\|(?:ht|f)tps?\:\/\/)[^ \/\]+([\/\].)?|(?!\\|(?:ht|f)tps?\:\/\/).)$