Can anyone help me please? It is for mod-rewrite in .htaccess
From this url file name:
car-audi-tt-2
I need to get the full string.
But if the string i get is this:
car-audi-tt-2-2019
I need to get (with the same regular expression) "car-audi-tt-2" in $1 and "2019" in $2.
Any idea?
Now i have this code, which it is working just for second case in https://www.regextester.com:
([-A-Za-z0-9\+\.]+)-(20[-0-9]{2})*
You need to also make the
-(hyphen) delimiter (before the last "year") optional. But only optional when the "year" is present and do not include this in the capturing subpattern.You should also anchor the regex (although this may depend on your
RewriteRuledirective), since you need to make the+quantifier on the first subpattern non-greedy so to not consume the now optional "-year".[-0-9]- As I queried in comments, the first hyphen in the 2nd character class looks out of place and does not match your example. I've removed it in my solution below and in doing so simplified the regex.There is no need to backslash-escape the literal
+and.characters inside the character class.Try the following instead:
The
?:prefix on the parenthesized subpattern makes it non-capturing. This is so that the nested capturing subpattern becomes the 2nd capturing group (ie.$2).The
?quantifier makes the "-year" optional, whereas*allows for an unlimited number of repetitions (including none), which could potentially result in part of the filename being "lost" (since the backreference only contains the last match).Aside:
If using mod_rewrite then you don't necessarily need to do this in a single rule/regex.