Extracting values from function/list containing arguments/elements (using patterns)

Here are two approaches:

  • Using BlankNullSequence (___) and OrderlessPatternSequence:

    {
      f[x1, a -> 1, b -> 2],
      f[x2, b -> 2, a -> 1],
      f[x3, c -> 2, a -> 1, d -> 5, b -> 2, e -> 6],
      f[x4, e -> 5, b -> 2, c -> 2, a -> 1, d -> 3]
      } /. f[x_, OrderlessPatternSequence[___, a -> 1, ___, b -> 2, ___]] :> x
    (* {x1, x2, x3, x4} *)
    
  • Using Condition (/;):

    {
      f[x1, a -> 1, b -> 2],
      f[x2, b -> 2, a -> 1],
      f[x3, c -> 2, a -> 1, d -> 5, b -> 2, e -> 6],
      f[x4, e -> 5, b -> 2, c -> 2, a -> 1, d -> 3]
     } /. f[x_, opts__Rule] /; ({a, b} /. {opts}) == {1, 2} :> x
    (* {x1, x2, x3, x4} *)
    

list /. _[v_, opts : OptionsPattern[]] /; 
  FilterRules[{opts}, {target}] != {} :> "extractedValue" -> v

{SomeFunction[v1, arg -> "val"],
"extractedValue" -> v2,
"extractedValue" -> v3}

Alternatively, use the same replacement rule with Replace at level 1:

Replace[list, _[v_, opts : OptionsPattern[]] /; 
   FilterRules[{opts}, {target}] != {} :> "extractedValue" -> v, 1]

{SomeFunction[v1, arg -> "val"],
"extractedValue" -> v2,
"extractedValue" -> v3}