# The best way to return a matched expression

I need to store or use a matched pattern, as I need it later on. I'd like it so that the match is NOT confined in a pattern-like syntax like:

pattern /; test
lhs :> rhs /; test
lhs := rhs /; test


or

pattern ? test


So I've been using this:

MatchQ[expr, x:pattern /; (var = x; True)]


Is there a neater way to do it, like:

var = MatchQ[expr, x:pattern extracode]

• I suspect that you meant var==x. Could you provide a simple example of some inputs and the desired outputs? – Jack LaVigne Nov 5 '16 at 23:36
• I then use var. If I want a return mechanism in a function (which has a Block or Module inside), I return var. – kozner Nov 6 '16 at 2:03
• Would Cases perhaps do what you have in mind? – Daniel Lichtblau Nov 6 '16 at 19:29

It is difficult to discern from your question what you're actually trying to do. Daniel mentioned Cases, and maybe you could use that. If not you could use a utility function in a PatternTest like this:

set = (var = #; True) &;

MatchQ[{1, 2, 3}, (x : _List)?set]

var

True

{1, 2, 3}


This particular pattern could also be written concisely as x_List?set.

Also consider Sow and Reap:

sow = (Sow@#; True) &;

MatchQ[{1, 2, 3}, (x : _List)?sow] // Reap

{True, {{{1, 2, 3}}}}