Finding Expressions That Match a Pattern

Finding elements that match a pattern.

This gives the elements of the list which match the pattern x^_:

Cases[{3,4,x,x^2,x^3},x^_]

Here is the total number of elements which match the pattern:

Count[{3,4,x,x^2,x^3},x^_]

You can apply functions like (RefLink[Cases, paclet:ref/Cases]) not only to lists, but to expressions of any kind. In addition, you can specify the level of parts at which you want to look.

Searching for parts of expressions that match a pattern.

This returns a list of the exponents n:

Cases[{3,4,x,x^2,x^3},x^n_->n]

The pattern _Integer matches any integer. This gives a list of integers appearing at any level:

Cases[{3,4,x,x^2,x^3},_Integer,Infinity]

Limiting the number of parts to search for.

This gives the positions of the first two powers of x appearing at any level:

Position[{4,4+x^a,x^b,6+x^5},x^_,Infinity,2]

The positions are specified in exactly the form used by functions such as (RefLink[Extract, paclet:ref/Extract]) and (RefLink[ReplacePart, paclet:ref/ReplacePart]) discussed in "Lists":

ReplacePart[{4,4+x^a,x^b,6+x^5},Thread[%->zzz]]

Deleting parts of expressions that match a pattern.

This deletes the elements which match x^n_:

DeleteCases[{3,4,x,x^2,x^3},x^n_]

This deletes all integers appearing at any level:

DeleteCases[{3,4,x,2+x,3+x},_Integer,Infinity]

Finding arrangements of an expression that match a pattern.

This finds all ways that the sum can be written in two parts:

ReplaceList[a+b+c,x_+y_->g[x,y]]

This finds all pairs of identical elements. The pattern ___ stands for any sequence of elements:

ReplaceList[{a,b,b,b,c,c,a},{___,x_,x_,___}->x]