Jingguo Yao
Jingguo Yao

Reputation: 8006

What are the precedence rules for Perl regular expressions?

I can find't an official reference for the precedence rules for Perl regular expressions. What I can find is only Know the precedence of regular expression operators. However, it's not an official reference given by perldoc.

Upvotes: 5

Views: 637

Answers (1)

ikegami
ikegami

Reputation: 386541

Regular expressions only have two binary operators, one of which is implicit rather than represented by a symbol. Regular expressions also have a number of unary operators, but their precedence is moot due to the restrictions on their operands. That makes talking about precedence really odd.

It's simpler conveying the information you seek using the following statements:

  • Quantifiers modify a single atom.
  • Quantifiers modifiers modify a single quantifier.
  • Alternation is unbounded except by the parens in which they reside.

The above information is conveyed one way or another in perlretut.


That said, it is possible to build a precedence table. Since the above statements convey all the information you need, it's possible to build the precedence table from them. It is the following:

  1. Atoms (e.g. a, \n, \^, ., ^, \w, [...], \1, (...))
  2. Postfix unary operators (quantifiers and quantifier modifiers)
  3. Implicit "followed by" operator between (possibly-quantified) atoms
  4. Alternation

This matches the chart in the page to which you linked.


For fun, the following would be the BNF:

pattern              ::= <alternation>

alternation          ::= <sequence> <alternation2>
alternation2         ::= "|" <alternation> | ""

sequence             ::= <quantified_atom> <sequence> | ""

quantified_atom      ::= <atom> <quantified_atom2>
quantified_atom2     ::= <modified_quantifier> | ""
modified_quantifier  ::= <quantifier> <modified_quantifier2>
modified_quantifier2 ::= <quantifier_modifier> | ""

Upvotes: 5

Related Questions