Your regex has too many capturing groups.
Using (?:)
makes it into a simple matching group, speeding up the regex since it doesn't have to store anything.
Since you are trying to get the part from the end of the string, anchor it there using $
.
At the end, you have this: (\/)(\w+\.\w+)
.
This is really bad in 2 ways:
- You are using 2 capturing groups.
- You regex only allows files with letters. Spaces, underscores and others should de allowed too.
For version control, you have this: (\/)(\w\d-?\d)
.
This allows me to have a folder called t0-0
which makes no sense.
Be more strict about your match.
This is the regex I came up with:
\/(?:[vV][1-9]\d?(?:-\d)?\/)?[^\/]+\.[^\.]+$
It addresses all your issues.
Explaining each part:
(?:\/[vV][1-9]\d?(?:-\d)?\/)?
matches the version number, if there is any.
1.1. No need for capturing groups.
1.2. It enforces that the folder starts with v or V with.
1.3. The version only can starts with 1-9
and can have any number or digits.
1.4. The version folder is still optional
[^\/]+\.[^\.]+$
matches the file name.
2.1. Again: No need for capturing groups.
2.2. The file can have ANY name.
2.3. The file can have ANY extension, but there must be one.
- The whole string is matched to the end, which makes it easier for us to write it.
/([/][^/]+)?([/].+)$/
\$\endgroup\$.+
with[^/]+
\$\endgroup\$resources/services/dealerInfoRequest/f/dealerInfoRequestManager.cfc
(replace/f/
by anything between/
and it will match). The OP didn't specified if it is a requirement to keep the same format in the string. But I really like your solution. \$\endgroup\$