When I name a pattern I'm working with, that name stands for the same particular expression wherever it shows up. That's a basic precept of how the Wolfram Language's pattern-matching works. But if I want to keep the generality of some pattern, how can I avoid naming it when applying a condition? That's a little hard to articulate, so let me give a specific example.
endsWithSpaceQ[str_] := StringEndsQ[str, " "];
str1 = "abc efg 17";
str2 = "abc abc 17";
I want to test str1
and str2
to see if they match the pattern
Repeat[substring-that-satisfies-endsWithSpaceQ, {2}] ~~ "17"
It's natural to start with:
StringMatchQ[#,
Repeated[p__ /; endsWithSpaceQ[p], {2}] ~~ "17"] & /@ {str1, str2}
However, this returns {False, True}
, because since I named the pattern p__
, Mathematica looks for two occurrences of a particular string that satisfy my condition. Instead, I want two substrings, not necessarily identical, that satisfy the condition. ?
allows me to use pure functions so I can avoid the necessity for /; f[]
to take an argument (i.e. the name of my pattern), but ?
does not test an entire substring [sequence for non-string patterns] but rather its individual characters [elements of the sequence].
Is there any way I can use Condition
without forcing myself to name the pattern? If not, I'm looking specifically for a way to require the anonymous pattern inside Repeated[__]
to satisfy a condition.
(Help with the title is encouraged -- I can't find anything to sum this question up well)
Edit: clarification Of course, my real-life task is a little more complicated than this example. I'm hoping for a general solution or solution-strategy, because I think it'd be good to have on record here. If one isn't out there, I might post another question with my specific problem (assuming I can't hack it together myself).