Alright, let's start with the regular expression and then move on to the explanation:
(?<folderorurl>(?<folder>(\\[^\\\s",<>|]+)+)|(?<url>https?:\/\/[^\s]+))
The first condition is to match a folder name that should not contain any characters like ", <, >, or |, as well as no whitespaces. This part is denoted as:
[^\s,<>|] # using the caret to negate the character class
In addition, we want to allow for optional subfolders following the main folder name. To achieve this, we need to include a backslash in the character class:
[^\\\s,<>|] # including a backslash in the character class
We also aim to match one or more characters while making sure there is at least one match, which is indicated by the plus sign (+
). Consider the example string:
\server\folder
Currently, only "server" is being matched, so we add a backslash to match "\server". Since file paths consist of a backslash followed by a folder name, we need to match this pattern multiple times (but at least once):
(\\[^\\\s",<>|]+)+
To improve readability, a named capturing group ((?<folder>)
) is used:
(?<folder>(\\[^\\\s",<>|]+)+)
This will now match strings like \server
or
\server\folder\subfolder\subfolder
and save them in a group labeled
folder
.
Next, let's move on to the URL part. A URL typically starts with http or https, followed by a colon, two forward slashes, and additional content:
https?:\/\/[^\s]+ # additional content must not have whitespaces
Following the same logic, this is stored in a named group called "url":
(?<folder>(\\[^\\\s",<>|]+)+)
Keep in mind that this regex may match invalid URLs (e.g.,
https://www.google.com.256357216423727...
). If this behavior is acceptable, you're good to go. Otherwise, you might want to refer to this question on SO.
Finally, let's combine these elements using an or, store them in another named group ("folderorurl"), and we're finished. Pretty simple, right?
(?<folderorurl>(?<folder>(\\[^\\\s",<>|]+)+)|(?<url>https?:\/\/[^\s]+))
Now, either a folder name or a URL can be found in the folderorurl
group while still retaining the individual parts in url
or folder
. While I'm not familiar with angular.js, this regex should give you a good starting point. You can also check out this regex101 demo for a working example.