MathGroup Archive 2005

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: string pattern search

>-----Original Message-----
>From: zak [mailto:chocolatez at] 
To: mathgroup at
>Sent: Tuesday, May 24, 2005 11:13 AM
>Subject: [mg57373] [mg57305] string pattern search
>how to search for the pattern "abc" in the string 
>and the letters space between a,b,c is not important, so the 
>output will be:
>1-when overlapping not allowed:
>2-and when we consider overlapping:

I can't help you with string pattern matching as my Mathematica version
is old (4.1) :-( but I might illustrate pattern matching in general 

First "abc" is not yet a "pattern" to give the matches indicated, you
would allow arbitrary characters in between.

The task of matching characters in a stream can be mapped to matching
elements in a list by 

In[1]:= xx = Characters["aiibbaecXXacarbiiicc"]
{"a", "i", "i", "b", "b", "a", "e", "c", "X", "X", "a", "c", "a", "r",
"i", "i", "i", "c", "c"}

When you want "non overlapping matches", repeatedly try on your list
keeping only the still unmatched parts. You can travel down the list
easily with FixedPoint, and to collect the results use FixedPointList:

FixedPointList[ Replace[Last[#],
{StringJoin["a",atr,"b",btr,"c"], {rest}}, _:> {stop}}]&, {xx}];

In[3]:= Take[%,{2,-3}][[All,1]]
Out[3]= {"aiibbaec", "acarbiiic"}

When you consider overlapping, you obviously retry after moving away
from the first matching "a"; such accordingly:

FixedPointList[ Replace[Last[#],
{StringJoin["a",atr,"b",btr,"c"], {atr,"b",btr,"c",rest}}, _:>
{stop}}]&, {xx}];

In[5]:= Take[%,{2,-3}][[All,1]]
{"aiibbaec", "aecXXacarbiiic", "acarbiiic", "arbiiic"}

These are, however, not all possible matches. The Mathematica machinery
for that is ReplaceList:


In[7]:= First/@Split[%]
{"aiibbaec", "aiibbaecXXac", "aiibbaecXXacarbiiic", "aecXXacarbiiic", 
"acarbiiic", "arbiiic", "aiibbaecXXacarbiiicc", "aecXXacarbiiicc", 
"acarbiiicc", "arbiiicc"}

Here I identified those matches which just differ on the position of the
"intermediate" matching "b" (with same matching positions for "a" and

If you want to see all posible matches, indicating the matching
positions, you might like to evaluate this:

{h___,"a",atr___,"b",btr___,"c",t___}:> GridBox[{Join[{h},StyleForm[#,
FontWeight->"Bold", FontColor->Hue[0,1,.7]]&
{Sequence@@Table[" ",{Length[{h}]}],
"\[UpArrow]",Sequence@@Table[" ",{Length[{atr}]}],
"\[UpArrow]",Sequence@@Table[" ",{Length[{btr}]}],"\[UpArrow]",
Sequence@@Table[" ",{Length[{t}]}]}}]

The matching part here is highlighted, arrows indicate the positions of
the matching characters.

Hartmut Wolf

  • Prev by Date: Re: Re: Mapping Data
  • Next by Date: Re: Solve or Reduce on a monstrosity of an expresssion (and a prize!)
  • Previous by thread: Re: string pattern search
  • Next by thread: Re: string pattern search