In Perl RegEx, we have the look-ahead/behind feature; it there a similar functionality available for Wolfram Language patterns?

Re @mikado:

  • Suppose we have a random expression in FullForm, something like (do forgive me for writing this like lousy json):
    h22[l221, l222]
    h32[l221, l222]

where I would hope to select (restricted to the first level) all the cases of Sequence[h1[___],h2[h21[],___]] between a l1 and a h3[_,h32[__]]. What's the way to do this?

  • 2
    $\begingroup$ Can you give an example of an expression you would like to match? $\endgroup$
    – mikado
    Jun 24 at 7:47

The matching you're looking for in this case is via SequenceCases, I think, which represents a subsequence to match as a list—so, for example, SequenceCases[{a,a,b,c,b}, {_,b}] extracts {{a,b}, {c,b}}.

But, you can also wrap your pattern in a rule which will match the lhs and replace it with the rhs. The standard way to implement "matching environments" like look-aheads and look-behinds in Mathematica (as far as I'm aware) is to use a rule of the form {preceding : <patt0>, p : <extractedpatt>, following : <patt1>} :> p. This essentially matches the full sequence (including the look ahead/behind pattern) and then replaces it with what's in the middle.

SequenceCases also requires that the head of the to-be-extracted-from expression is List. So:

SequenceCases[List @@ H[<...>],
    {l0, p : PatternSequence[h1[___],h2[h21[],___]], h3[_,h32[__]]} :> {p}]

This should give a list of subsequences that are matched enclosed by List, i.e. something like {{h1[<...>], h2[h21[],<...>]}, {h1[<...>], h2[h21[],<...>]}, <...>}.

  • $\begingroup$ Thanks a lot! I've used SequenceCases before, but it didn't occur to me that it could be used as such. I come to realize that the patterns of MMA is as expressive for S-exprs as regex is for strings (which must have been obvious for a wiser man). $\endgroup$
    – Gravifer
    Jun 25 at 0:04
  • 1
    $\begingroup$ Btw I'm a little unsatisfied with WRI's naming. Maybe it would be more accurate to tern SequenceCases[] and related functions as Splice*[], as they require wrapping the actual pattern with {} and only works with Lists, conforming to the syntax and semantics of Splice. $\endgroup$
    – Gravifer
    Jun 25 at 0:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.