Answer the question
In order to leave comments, you need to log in
A tricky regexp?
Task: from a domain name of the form part1.part2.part3.part4 to get a domain of the form part2.part3.part4 using capture groups
part1 and part2 may be absent
if part2 is absent (second-level domain), then get the domain www.part3.part4
As a result, it should work so:
www.subdomain.domain.ru -> subdomain.domain.ru
subdomain.domain.ru -> subdomain.domain.ru
www.domain.ru -> www.domain.ru
domain.ru -> www.domain.ru
The use of capture groups is fundamental.
Is it possible to solve the problem within PCRE?
The question can also be formulated as: how to set a value for the capture group in PCRE if it looks like (.+)? and did not match.
Answer the question
In order to leave comments, you need to log in
I'm not sure, but regular expressions don't seem to be able to freely modify and return content beyond what was in the original string. If this is true, I think it is obvious that the problem cannot be completely solved within the framework of PCRE.
server_name "~^(?\w+\.)?(?\w+\.)?(?\w+\.)(?\w+)$"
if ($part2 = "") {$part2 = "www"; }
return 301 http://$part2$part3$part4
server_name s"~^(?\w+\.)?(?\w+\.)?(?\w+\.)(?\w+)$"htttp://(?($part2)www|)$part3 $part4"g
Of course, if the language supports the construction (?(n)then|else). Such a construction can be written using lookback checks.
PS
Don't blame the syntax, I don't know the exact rules
But if I were you, I'd just add 'www.' on the left and just use a regular expression like
$_ = "www." +serverName;
s/^(?:\w+\.){0,2}(\w+\.\w+\.\w+)$/$1/g
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question