Объяснение регулярных выражений - PullRequest
3 голосов
/ 10 декабря 2011

Я довольно новичок в регулярных выражениях, и недавно я наткнулся на регулярное выражение в сценарии perl, которое я не мог понять:

$groups= qr/\(([^()]+|(??{$groups}))*\)/;

Любая помощь будет оценена!

Ответы [ 2 ]

10 голосов
/ 10 декабря 2011

Хорошо, если вы расширите его:

$groups= qr/
  \(                 # match an open paren (
    (                # followed by
      [^()]+         # one or more non-paren character
    |                # OR
      (??{$groups})  # the regex itself
    )*               # repeated zero or more times
  \)                 # followed by a close paren )
/x;

Вы получаете элегантный рекурсивный подход для поиска сбалансированных скобок:)

2 голосов
/ 10 декабря 2011

Модуль YAPE :: Regex :: Explain может рассказать вам, что делает регулярное выражение:

% perl5.14.2 -MYAPE::Regex::Explain -E 'say YAPE::Regex::Explain->new(shift)->explain' '\(([^()]+|(??{$groups}))*\)'
The regular expression:

(?-imsx:\(([^()]+|(??{$groups}))*\))

matches as follows:

NODE                     EXPLANATION
----------------------------------------------------------------------
(?-imsx:                 group, but do not capture (case-sensitive)
                         (with ^ and $ matching normally) (with . not
                         matching \n) (matching whitespace and #
                         normally):
----------------------------------------------------------------------
  \(                       '('
----------------------------------------------------------------------
  (                        group and capture to \1 (0 or more times
                           (matching the most amount possible)):
----------------------------------------------------------------------
    [^()]+                   any character except: '(', ')' (1 or
                             more times (matching the most amount
                             possible))
----------------------------------------------------------------------
   |                        OR
----------------------------------------------------------------------
    (??{$groups})            run this block of Perl code (that isn't
                             interpolated until RIGHT NOW)
----------------------------------------------------------------------
  )*                       end of \1 (NOTE: because you are using a
                           quantifier on this capture, only the LAST
                           repetition of the captured pattern will be
                           stored in \1)
----------------------------------------------------------------------
  \)                       ')'
----------------------------------------------------------------------
)                        end of grouping
----------------------------------------------------------------------

Вы можете превратить эту строку в псевдоним в своем профиле:

alias re="perl -MYAPE::Regex::Explain -E 'say YAPE::Regex::Explain->new(shift)->explain'"

После этого вам не нужно запоминать все это:

re '\(([^()]+|(??{$groups}))*\)'
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...