I have arrived at a regex for file path that has these conditions,
- Must match regex
^(\\\\[^\\]+\\[^\\]+|https?://[^/]+), so either something like \server\share (optionally followed by one or more "\folder"s), or an HTTP(S) URL - Cannot contain any invalid path name chars( ",<,>, |)
How can i get a single regex to use in angular.js that meets these conditions
Ok, first the regex, than the explanation:
Your first condition is to match a folder name which must not contain any character from ",<>|" nor a whitespace. This is written as:
Additionally, we want to match a folder name optionally followed by another (sub)folder, so we have to add a backslash to the character class:
Now we want to match as many characters as possible but at minimum one, this is what the plus sign is for (
+). With this in mind, consider the following string:At the moment, only "server" is matched, so we need to prepend a backslash, thus "\server" will be matched. Now, if you break a filepath down, it always consists of a backslash + somefoldername, so we need to match backslash + somefoldername unlimited times (but minimum one):
As this is getting somewhat unreadable, I have used a named capturing group (
(?<folder>)):This will match everything like
\serveror\server\folder\subfolder\subfolderand store it in the group calledfolder.Now comes the URL part. A URL consists of http or https followed by a colon, two forward slashes and "something afterwards":
Following the explanation above this is stored in a named group called "url":
Bear in mind though, that this will match even non-valid url strings (e.g.
https://www.google.com.256357216423727...), if this is ok for you, leave it, if not, you may want to have a look at this question here on SO.Now, last but not least, let's combine the two elements with an or, store it in another named group (folderorurl) and we are done. Simple, right?
Now the folder or a URL can be found in the
folderorurlgroup while still saving the parts inurlorfolder. Unfortunately, I do know nothing about angular.js but the regex will get you started. Additionally, see this regex101 demo for a working fiddle.