Naming Pieces of Patterns

Particularly when you use transformation rules, you often need to name pieces of patterns. An object like x_ stands for any expression, but gives the expression the name x. You can then, for example, use this name on the righthand side of a transformation rule.

An important point is that when you use x_, the Wolfram Language requires that all occurrences of blanks with the same name x in a particular expression must stand for the same expression.

Thus f[x_,x_] can only stand for expressions in which the two arguments of f are exactly the same. f[_,_], on the other hand, can stand for any expression of the form f[x,y], where x and y need not be the same.

The transformation rule applies only to cases where the two arguments of f are identical:
Click for copyable input

The Wolfram Language allows you to give names not just to single blanks, but to any piece of a pattern. The object x:pattern in general represents a pattern which is assigned the name x. In transformation rules, you can use this mechanism to name exactly those pieces of a pattern that you need to refer to on the righthand side of the rule.

_any expression
x_any expression, to be named x
x:patternan expression to be named x, matching pattern

Patterns with names.

This gives a name to the complete form _^_ so you can refer to it as a whole on the righthand side of the transformation rule:
Click for copyable input
Here the exponent is named n, while the whole object is x:
Click for copyable input

When you give the same name to two pieces of a pattern, you constrain the pattern to match only those expressions in which the corresponding pieces are identical.

Here the pattern matches both cases:
Click for copyable input
Now both arguments of f are constrained to be the same, and only the first case matches:
Click for copyable input