M
M
Maxim2013-08-27 16:27:33
Perl
Maxim, 2013-08-27 16:27:33

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

5 answer(s)
U
UZER2006, 2013-08-27
@UZER2006

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.

N
noonesshadow, 2013-08-27
@noonesshadow

server_name "~^(?\w+\.)?(?\w+\.)?(?\w+\.)(?\w+)$"
if ($part2 = "") {$part2 = "www"; }
return 301 http://$part2$part3$part4

Y
Yaroslav Astafiev, 2013-08-28
@kentilini

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

Y
Yaroslav Astafiev, 2013-08-28
@kentilini

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

V
vsespb, 2013-08-30
@vsespb

PCRE, despite standing for Perl Compatible Regular Expressions, is not related to Perl. Regexps are different in Perl. PCRE is just trying to make them similar.
(this is me to the question of the name of the hub)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question