Comparing parts of patterns by name

Let's say I wanted to pick out all the rows of a table for which columns 3 and 5 are equal. The following doesn't work, as the second x is treated as an independent variable.

Cases[table, {_, _, x_, _, x, ___}]


How do I make sure x is recognized "outside itself", so to speak?

• I believe simply making the other x a pattern as well works! I.e., Cases[table, {_, _, x_, _, x_, ___}] The use of x without the underscore is used when it's not literally in the matched expression, but is just something you're doing with the matched expression once you've got it—e.g. on the rhs of a rule, x_ :> x, or on the rhs of a definition, f[x_] := x – thorimur May 26 at 1:19
• @thorimur Say I wanted the 5th column to have x^2 instead; how would I do that? (x_)^2 doesn't work. – Blrp May 26 at 23:54
• ah, yeah, because pattern matching tests the syntax of things, but that's a question of numeric equality, not syntax. If you still want to use pattern-matching, then for that I'd recommend using condition (/;), which lets you demand some condition holds of the matched pattern, and can be read as "such that". So, for example, Cases[table, {_, _, x_, _, y_, ___} /; y == x^2] However, you could also use Select here: Select[table, #[[5]] == #[[3]]^2 &] – thorimur May 27 at 0:02
• (I'm going to just convert this to an answer in the interest of "stack hygiene"...) – thorimur May 27 at 0:09

I believe simply making the other x a pattern as well works! I.e., Cases[table, {_, _, x_, _, x_, ___}].
The use of x without the underscore is used when it's not literally in the matched expression, but is just something you're doing with the matched expression once you've got it—e.g. on the rhs of a rule, x_ :> x, or on the rhs of a definition, f[x_] := x.
Say I wanted the 5th column to have x^2 instead; how would I do that? (x_)^2 doesn't work. — Blrp
Ah, yeah, that's because pattern matching tests the syntax of things, but this is a question of numeric equality, not syntax. If you still want to use pattern-matching, then for that I'd recommend using Condition (/;), which lets you demand some condition holds of the matched pattern, and can be read as "such that". So, for example, Cases[table, {_, _, x_, _, y_, ___} /; y == x^2]
However, given the "criterion-like" nature of this, you could equivalently use Select here, and it might be a bit more concise: Select[table, #[[5]] == #[[3]]^2 &]