Docsity

Approximate String Matching: Algorithms and Extensions, Study notes of Computer Science

Toggle sidebar
bg1
Sun Wu and Udi Manber
Fast
i-. i
Errors
The
string-matching problem
is a
very common problem.
We
are searching for a string
P = PtP2..
"Pro
inside a large text
file T =
tlt2...t.,
both
sequences of
characters
from
a finite
character set
Z. The
characters may be English characters in a
text file, DNA base pairs, lines of source code, angles between
edges in polygons, machines or machine parts in a production
schedule, music notes and tempo in a musical score, and so
forth. We want to find all
occurrences of
P in T; namely, we
are searching for the set of starting positions F =
{i[1
--- i--- n - m + 1 such that
titi+
l""ti+ m - 1 = P}" The two
most
famous algorithms for this problem are
the Boyer-Moore
algorithm [3] and
the Knuth
Morris Pratt algorithm
[10].
There are many extensions
to this
problem; for example,
we
may be looking for a set of patterns, a pattern
with
"wild
cards," or a regular expression. String-matching tools are
included in every reasonable text editor, word processor,
and many other applications.
In some instances, however, the
pattern and/or the text are not
exact. For example, we may not
remember the exact spelling of a
name we are searching, the name
may be misspelled in the text, the
text may correspond to a sequence
of numbers with a certain property
and we do not have an exact pat-
tern, the text may be a sequence of
DNA molecules and we are looking
for approximate patterns. The
approximate string-matching prob -"
lem is to find all substrings in T that
are
close
to P under some measure
of closeness. The most common
measure of closeness is known as
the edit distance (also the
Levenshtein measure [13]). A string
P is said to be of distance k to a
string Q if we can transform P to be
equal to Q with a sequence of k in-
sertions of single characters in (ar-
bitrary places in)
P,
deletions of sin-
gle characters in P, or substitutions
of characters. In some cases we may
want to define closeness differently.
For example, a policeman may be
searching for a license plate
ABC123 with the knowledge that
the letters are correct, but there
may be an error with the numbers.
In this case, a string is of distance 1
to ABC123 if only one error occurs
and it is within the digits area.
Maybe there are always three digits
in a license plate, in which case only
substitutions are allowed. Some-
times one wants to vary the cost of
the different edit operations, say
deletions cost 3, insertions 2, and
substitutions 1.
Many different approximate
string-matching algorithms have
been suggested ([4, 5, 6, 8, 11, 12,
16, 19, 20] is a partial list). In this
article we present a new algorithm
which is very fast in practice, rea-
sonably simple to implement, and
supports a large number of varia-
tions of the approximate string-
matching problem. The algorithm
is based on a numeric scheme for
exact string matching developed by
COMMUNICATIONS OF THE
ACM/October 1992/Vol.35, No.10
83
pf3
pf4
pf5
pf8
pf9

Partial preview of the text

Download Approximate String Matching: Algorithms and Extensions and more Study notes Computer Science in PDF only on Docsity!

Sun Wu and Udi Manber

F a s t

i -. i

E r r o r s

T h e string-matching problem is a very c o m m o n problem.

We are searching for a string P = PtP2.. "Pro i n s i d e a l a r g e t e x t

file T = tlt2...t., b o t h sequences of characters from a f i n i t e

character set Z. T h e characters may be English characters in a

text file, D N A base pairs, lines of source code, angles between

edges in polygons, machines or machine parts in a production

schedule, music notes and tempo in a musical score, and so

f o r t h. We w a n t to f i n d a l l occurrences of P i n T; n a m e l y , we

are searching for the set of starting positions F = {i[

--- i--- n - m + 1 s u c h t h a t titi+ l " " t i + m - 1 = P } " T h e t w o most

famous algorithms for this problem are t h e B o y e r - M o o r e

algorithm [3] and t h e K n u t h Morris Pratt algorithm [10].

There are many extensions to t h i s problem; for example, we

may be looking for a set of patterns, a pattern w i t h " w i l d

cards," or a regular expression. String-matching tools are

included in every reasonable text editor, word processor,

and many other applications.

In some instances, however, the pattern and/or the text are not exact. For example, we may not r e m e m b e r the exact spelling of a name we are searching, the name may be misspelled in the text, the text may correspond to a sequence of n u m b e r s with a certain property and we do not have an exact pat- tern, the text may be a sequence of DNA molecules and we are looking

for approximate patterns. T h e approximate string-matching prob -" lem is to find all substrings in T that

are close to P u n d e r some measure

of closeness. T h e most c o m m o n measure of closeness is known as the edit distance (also the Levenshtein measure [13]). A string P is said to be of distance k to a string Q if we can transform P to be equal to Q with a sequence of k in-

sertions of single characters in (ar-

bitrary places in) P, deletions of sin-

gle characters in P, or substitutions of characters. In some cases we may want to define closeness differently. For example, a policeman may be searching for a license plate ABC123 with the knowledge that the letters are correct, but there may be an error with the numbers. In this case, a string is of distance 1 to ABC123 if only one error occurs and it is within the digits area. Maybe there are always three digits in a license plate, in which case only substitutions are allowed. Some- times one wants to vary the cost of the different edit operations, say deletions cost 3, insertions 2, and substitutions 1. Many different approximate string-matching algorithms have been suggested ([4, 5, 6, 8, 11, 12, 16, 19, 20] is a partial list). In this article we present a new algorithm which is very fast in practice, rea- sonably simple to implement, and supports a large n u m b e r of varia- tions of the approximate string- matching problem. T h e algorithm is based on a numeric scheme for exact string matching developed by

COMMUNICATIONSOF THE ACM/October 1992/Vol.35, No.10 8 3

Baeza-Yates and G o n n e t [2]. T h e algorithm can handle most of the c o m m o n types of queries, including arbitrary regular expressions, and several variations of closeness mea- sures. In o u r experiments, the algo- rithm was at least twice as fast as other algorithms we tested (which are not as flexible), and for many cases an order of magnitude faster. For example, finding all occur-

rences of Homogenos allowing two

errors in a 1MB bibliographic text takes about 0.4 sec on a SUN SparcStation II. We actually used this example a n d found a misspell- ing in our text. T h e algorithms in this article served as a basis for a software

package for Unix called agrep,

which has been in use since J u n e

  1. Agrep, which at the date of this writing is at version 2.04, is available by a n o n y m o u s ftp from cs.arizona.edu. We describe agrep briefly at the end of this article. For more information see [15, 23, 24]. We begin by describing the algo- rithm for the pure string-matching problem (i.e., the pattern is a simple string). We then present many vari- ations and extensions of the basic algorithm, culminating with match- ing arbitrary regular expressions with errors. Experimental results are given, as are details of agrep.

The Algorithm

We first describe the case of exact string matching. T h e algorithm for this case is essentially identical to that of [2]. We present it here for completeness a n d because we use a slightly different notation. We then show how to extend the algorithm to search with errors. We then de- scribe how to speed up the search

with errors by using afiltering search

technique.

Exact MatChing

Let R be a bit array of size m (the size of the pattern). We denote by

Rj the value of the array R after the

j character of the text has been pro-

cessed. T h e array Rj contains infor-

mation about all matches of pre- fixes of P that end at j. More

precisely, Rj[i] = 1 if the first i char-

acters of the pattern match exactly the last i characters up to j in the

text (i.e., P]P2...i = tj-i+ltj-l+e...tj).

W h e n we read tj+l we need to de-

termine whether tj+l can extend

any of the partial matches so far.

For each i such that Rj[i] = 1 we

need to check whether tj+l is equal

to pi+l. IfRj[i] = 0 then there is no

match up to i a n d there cannot be a

match up to i + 1. If tj+l = pl then

Rj+][1] = 1. IfRj+l[m] = 1 then we

have a complete match, starting at j - m + 2, and we o u t p u t it. T h e

transition from Rj to Rj+x can be

summarized as follows: Initially, R0[k] = 0 for all k,

l ~ k < - m ,

and Rj[0] = 1, for all j, 0 --<j - n. f 1 if R j [ i - 1] = 1

Rj+l[i] = J a n d pi = tj+l

( 0 otherwise

If Rj+l[m] = 1 then we o u t p u t a

match at j - m + 2; This transition, which we have to compute once for every text char- acter, seems quite complicated. Other fast string-matching algo- rithms avoid the need to maintain the whole array. But, as observed by Baeza-Yates and Gonnet, this transition can be computed very fast in practice as follows. Let the alphabet be Z = Sl,S2..... slE[. For

each character si in the alphabet we

construct a bit array Si of size m

such that Si[r] = 1 if pT = si. (It is

sufficient to construct the S arrays only for the characters that appear

in the pattern.) In other words, Si

denotes the indexes in the pattern

that contain si. It is easy to verify

now that the transition from Rj to

Rj+ 1 a m o u n t s to no more than a

right shift of Rj and an AND opera-

tion with Si, where si = tj+ 1. So, each

transition can be executed with only two simple arithmetic operations, a shift a n d an AND. We assume that the right shift fills the first position with a 1. If only 0-filled shifts are available (as is the case with C), then we can add one more OR operation with a mask that has one bit. (Baeza-Yates and G o n n e t used 0 to indicate a match a n d an OR opera-

tion instead of an AND; that way, 0-filled shifts are sufficient. This is counterintuitive to explain, so we opted for the easier definition.) An example is given in Table la, where

the pattern is aabac a n d the text is

aabaacaabacab. T h e masks for ab

and c are given in Table lb. This discussion assumes, of course, that the pattern's size is no more than the word size, which is often the case. If the pattern's size is twice the word size, then four arith- metic operations will suffice. If the pattern is very large (e.g., in some biological applications the pattern size can be in the thousands), then other methods will be better. For most text-searching problems, small patterns are the norm. We discuss this issue later, but for now we will assume that the pattern's size is no more than the word size. This algorithm is clearly very easy to implement. Its r u n n i n g time is totally predictable because it essen- tially depends only on the size of the text (assuming again that the pattern fits into a word) a n d not on the actual text or the alphabet.

Approximate Matching

We now show how to adapt the pre- vious algorithm to allow errors. (Baeza-Yates and G o n n e t [2] showed how to handle only mis- matches by essentially counting k of them with a log2k size counter, but they did not handle insertions or deletions.) We start with a very sim- ple case: only one insertion is al- lowed into the pattern at any posi- tion. In other words, we want to find all intervals of size at most m + 1 in the text that contain the pat- tern as a subsequence. We define the R a n d S arrays as before, but now we have two possibilities for each prefix match. We can have an exact match or a match with one insertion. Therefore, we introduce

another array, denoted by R),

which indicates all possible matches

up to tj with at most one insertion.

More precisely, R)[i] = 1 if the first

i characters of the pattern match i of the last i + 1 characters up t o j in the text. If we can maintain both R

8 4 O c t o b e r 1992/Vol.35, No.IO/¢OMMUNWCATION$ OF THE A@M

following expression for Rd+l :

R~ = 11..100...000 d ones. Rd+t = Rshift[R d] AND Sc OR Rshift[R d-l] OR nshift[nd+~] OR R ~ - ' = Rshift[R ]] A N D Sc OR Rshift[R d-1 OR Rd+,I] OR n d-1. (2.1)

Overall, we have a total o f two shifts, one AND, and three ORs for each R d. T h e time and space analysis of the algorithm is as follows. Denote the word size by w. T h e preprocess- ing requires O(mJZJ) time and space, which is the same as the exact

matching algorithm, plus o(kJ J)

to initialize the k vectors. During the matching process, the algo- / r - ' I x rithm spends O(kJmJ) steps per

character. T h e r e f o r e , the total run-

ning time is O(nkJml). In cases \ I W l / where m is n o t t o o large, which are the cases the algorithm was de- signed for, the r u n n i n g time is ef- fectively O(nk). An i m p o r t a n t feature of this al- g o r i t h m is that it can be relatively easily e x t e n d e d to several more complicated patterns. Several such extensions will be described.

An Improvement to the Main Algorithm I f the n u m b e r of errors is small c o m p a r e d to the size of the pattern, then we can improve the r u n n i n g time sometimes by what we call the partition approach. Suppose again that the pattern P is of size m and that at most k errors are allowed.

Let r = , and let P1, P .....

Pk+l be the first k + 1 blocks of P

each of size r. In other words, P1 = Plp2...pT and Pj = p(j-1)r+l...Pjr. If r contains a match o f P with at most k errors, then at least one of the Pj's must be matched exactly. We can search for all Pj's at the same time (we discuss how to do that shortly) and, if one of them matches, then we check the whole pattern directly but only within a n e i g h b o r h o o d of

size m from the position of the match. Since we are looking for an exact match, there is no need to maintain all k of the R d vectors. This scheme will run fast if the n u m b e r o f exact matches to any o n e of the Pj's is n o t t o o high. T h e n u m b e r o f such matches d e p e n d s on many factors including the size of the alphabet, the actual text, and the values of r and m. For example, if r = 1, then we will need to check any time there is a character match, which is proba- bly too often. On the other hand, if r = 3, m = 12 (which implies k = 3), the alphabet size is 26, and the text is uniformly r a n d o m (i.e., each character appears with the same probability), the expected n u m b e r of matches of any o f the Pj's is about 0.02% of the time. In this case, it is obviously advantageous to search for exact matches and use the a p p r o x i m a t e scheme only for the rare occasions at which a match occurs. T h e r u n n i n g time in this case is essentially the same as the r u n n i n g time o f a search without errors. (Experiments using this partition scheme for different al- phabet sizes are given later.)

T h e main advantage o f this scheme is that the algorithm for exact matching presented earlier can be a d a p t e d in an elegant way to s u p p o r t it. We illustrate the idea with an example. Suppose the pat- tern is A B C D E F G H I J K L (m = 12) and k = 3. We divide the pattern into k + 1 = 4 blocks: ABC, DEF, G H I , and JKL. We need to find whether any of them appears in the text. We create one combined pat- tern by interleaving the four blocks: A D G J B E H K C F I L. We then build the mask vector R as usual for this interleaved pattern (see section o n Exact Matching). T h e only differ- ence is that, instead of shifting by o n e in each step, we shift by four! T h e r e is a match if any of the last four bits is 1. (When we shift we need to fill the first four positions with ls, or better yet, use shift-OR.) Thus, the match for all blocks can be done exactly the same way as

regular matches and it takes essen- tially the same r u n n i n g time.

Extensions An i m p o r t a n t feature of o u r algo- rithm is its flexibility. In addition to asking about a single string, the al- gorithm supports range of charac- ters (e.g., "0-9"), complements (e.g., everything except blank), arbitrary sets o f characters (e.g., {a,e,i,o,u}), unlimited "wild cards," and combi- nations. Searching for several strings at the same time is also pos- sible, although the size o f the pat- tern becomes the sum of the sizes o f the different strings (and might thus require m o r e than one word to represent). Except for the unlim- ited wild cards, all these extensions were developed by Baeza-Yates and Gonnet [2] for exact matching. We can apply them all to a p p r o x i m a t e matching in a straightforward man- ner. This is a major strength of the algorithm: most extensions (at least all those that we tried) that work f o r exact matching can also be used for a p p r o x i m a t e matching. Previous algorithms for a p p r o x i m a t e match- ing with complements or wild cards, for example, were quite com- plicated (see, for example, [1, 18]). T h e r u n n i n g time for all these ex- tensions is the same as the r u n n i n g time of the basic algorithm given earlier. In addition to these extensions, we also s u p p o r t two extensions that are specific to a p p r o x i m a t e match- ing. One deals with patterns in which some parts need to match exactly and other parts may contain errors. A n o t h e r extension is match- ing with some n o n u n i f o r m costs; for example, we can define the cost of insertions to be twice that of de- letions.

T h e most complicated patterns we can handle are arbitrary regular expressions. T h e ability to effi- ciently match regular expressions allowing errors enabled us to ex- tend the grep family and imple- ment the a p p r o x i m a t e pattern- matching tool agrep. We now de- scribe the extensions in more detail.

8 6 O c t o b e r 1 9 9 2 / V o 1. 3 5 , No.10/COMMUNICATIONS O F T H E ACM

sets of Characters Replacing one character with a set of allowable characters is very easy to achieve with this algorithm (as was shown in [2]). Suppose the pat- tern we want to find is ABC fol- lowed by one digit followed by XYZ, and that we allow up to k er- rors. We denote this pattern by ABC[0-9]XYZ. T h e only thing we need to do to accept any digit in the fourth position is to put 1 in the fourth position in the S arrays for all digits. T h a t is, in the preprocess- ing stage, when we decide for each character the positions that this character matches in the pattern, we include all the characters in the set within that position. T h e rest of the algorithm is identical with the regular algorithm. A complement of a character is a special case of a set of characters and it can obvi- ously be handled in the same way.

Wild Cards A single wild card is a symbol that matches all characters. As such, it is a special case of a set of characters and can be handled as we discussed in the previous section. Sometimes, however, we want to indicate that we allow an u n b o u n d e d n u m b e r of characters to appear in the middle of the pattern (or even do it several times in the middle of the pattern). This case requires modifying the algorithm slightly. Let the pattern be P = PlP2...Pm, and assume that the positions of "#" (which indi- cates unlimited wild cards in agrep) are after the characters pfi, pi 2..... Pis. (There is no reason to have two #'s in a row.) Let S° be a bit array that has 1 in exactly the positions il, i2, .... i,. T h e effect of putting a "#" following pi is as follows. If we are scanning tj and we find a match with up to d errors that ends at pi, then later when we scan tr, for any r > j , we can start matching tr to Pi+! no matter how many characters we skipped. In other words, if at some point there is a match up to Pi then this match is always valid later on (because all the characters later on can be considered as part of the ,,#,,).

We can adjust the algorithm for this case as follows. At each step, we apply the regular algorithm to com- pute all the R arrays. T h a t is, we compute R °, R] ..... R~ using (2.1). T h e n , for each i, 1 -< i -< d, we set = n'j o R [R~-I ' AND S#]. This step corresponds to the action "if at any point, there is a 1 entry in R i AND S °, then this entry should remain 1 from now on."

Unknown Number of Errors In some cases, we do not know the n u m b e r of errors a priori. We would like to find all occurrences of the pattern with the minimal n u m b e r of errors possible. T h e algorithm can be extended to this case as follows. We first try to find the pattern with no errors. If we are unsuccessful, we try with one error, then with three errors, then with 7 errors, and so on, essentially doubling the n u m b e r of errors (and adding one) at each attempt. If the n u m b e r of errors turns out to be k, then the r u n n i n g time will be O ( 1 - n + 2 " n + 4 - n + ' - ' + 2 b. n ) , where 20 is the first power of 2 greater than k. In the worst case, we perform 4 times as many opera- tions as we would have had we known k (in most cases, the factor is actually 2 or 3).

A Combination of Exact and Approximate Matching Sometimes we do not want to allow parts of the pattern to have errors. For example, we may look for li- cense plate ABC123, and we know that the letters are correct but the numbers may have one error in them. We denote this pattern by < A B C > 1 2 3. We can modify the algorithm to shield parts of the pat- tern from having any errors in them. Let's assume that I is the set of indexes in the pattern where no error is allowed, and let M be a masking array (of size m) that has a 0 in the indexes of I and a 1 other- wise. We would like to modify (2.1) such that insertions, deletions, a n d substitutions can only occur outside of I. This is done by masking these cases with M. T h e expression in

(2.1) is changed to

R~+, = [Rshift[Rd] AND Sc]

OR [[Rshift[R~-l OR R]+~]

O R R ] -1] A N D M ] (2.2)

Nonuniform Costs T h e edit distance measure assumes that insertions, deletions, and sub- stitutions all have the same cost. But in some cases, we want to allow fewer deletions, say, than substitu- tions, or maybe no deletions at all. T h e algorithm can be extended, albeit in a limited way, to the case in which each operation has a differ- ent cost. We illustrate this extension with an example: Suppose that sub- stitutions add 1 to the distance, but insertions and deletions add 3 each. Insertions and deletions are han- dled in cases 4 and 3 (see section 2). Insertions contribute the OR of R]-~ and deletions contribute the OR of Rshift[R~+~] (2.1). We would like them to cost 3 times as much. In other words, a deletion or inser- tion that leads to a match with d er- rors should come from a match with d - 3 errors. This can be achieved by simply replacing the d - 1 in both expressions with d -

  1. This modification is very simple and it does not add to the r u n n i n g time; however, it works only for small integer costs. (Another algo- rithm that allows different costs for different positions or different characters appears in [14].)

A Set of Patterns If we have several patterns and we want to find all occurrences of any of them, then we can either search them one at a time or together. T h e advantage of searching for all of them together is that it can be done in one scan (and in one command). Suppose we are looking for P1, Pz, .... Pr. We concatenate all the pat- terns and put them in one array (using as many words as needed), and apply the algorithm on that array with the following modifica- tions. Let M be a bit array the size of the combined pattern, and let bit i

COMMUNICATIONS OF THE ACM/October 1992/Vol.35, No.10 8 T

performance is sometimes better than the results in this section.

We tested the partition algorithm against two other algorithms, one by Ukkonen [20] (which we imple- mented) and one by Galil and Park [6] (labeled MN2; the program was provided for us by W.I. Chang) which is based on another tech- nique by Ukkonen [21]. These two algorithms are both improvements of the basic dynamic programming algorithm and their expected run- ning time is O(nk). We used random text (of size 1 million) and pattern (of size 20), and two different al- phabet sizes. In this case, since we use the idea of partitioning the pat-

tern, the size of the alphabet makes a big difference. A large alphabet leads to very few accidental exact matches, thus the running time is essentially the same as the one for exact matching. A small alphabet leads to many matches and the al- gorithm's performance degrades. T h e case of binary alphabet serves as the worst case for this purpose. Results are shown in Table 3. The second test was for more complicated patterns, including some of the extensions discussed in the previous section. (Anything within the < > brackets must match exactly; a " # " stands for a wild card of arbitrary length; a ";" serves as

Figure 1. The nondeterministlc automata corresponding to _ab(c~e)fg_*

Iruble l. Approximate string matching of simple strings

'robio 4. Approximate matching of complicated patterns

the Boolean AND operation, namely all patterns must appear within the same line; a "]" is the reg- ular expression union operation; and a "*" is the Kleene closure.) T h e results are given in Table 4 (the file was a bibliographic text of size 1MB). Another algorithm for approximate matching to arbitrary regular expressions is by Myers and Miller [ 17]. (Recently, we improved some parts of this algorithm [25].) T h e running times o f the Myers and Miller algorithm for the cases we tested, which include only small regular expressions and small er- rors, are more than an order of magnitude slower than our algo- rithm; however, this is not a fair comparison because their algo- rithm can handle more general cost functions and its running time is independent of the number of er- rors.

A Description o f Agrep Having such flexible algorithms motivated us to develop an approx- imate matching tool for Unix. Agrep has been in wide use since June 1991, and it has gone through two major revisions. It includes sev- eral new algorithms in addition to the ones described in this article (e.g., a new multipattern algorithm and an improved approximate string matching for simple strings). It is used similarly to grep/egrep/ fgrep and it supports most o f the features of the grep family (al- though it is not 100% compatible), but it supports many additional fea- tures (mostly but not all related to approximate matching). Agrep is at least as fast and in many cases faster than all other greps that we know of. One notable difference between agrep and the previous greps (be- sides the ability to search approxi- mately) is that agrep is record ori- ented (rather than line oriented). A record (e.g., a paragraph, a mail message) is defined by the user (with the default being a line). Agrep outputs all records that match the query (see the -d option described below). Agrep is avail- able, free of charge, by anonymous

COMMUNICATIONSOF THE ACM/Octobcr 1992/Vo1.35, No.10 8 9

ftp from cs.arizona.edu (IP n u m b e r 192.12.69.5). Next, we describe the unusual features of agrep that are not found in similar programs. A complete description is given in the manual pages distributed with agrep (see also [24]).

-d 'delim' delim is a user-defined symbol (or string) for record delimiter (the default is the new-line symbol). This enables searching p a r a g r a p h s (in which case delim = '$$') or mail messages (delim = '^From'). -k finds all occurrences with at most k errors (insertions, deletions, or substitutions), where k is a positive integer. -B finds all matches with m i n i m u m n u m b e r o f errors (e.g., if the best match has 2 errors, this is the same as r u n n i n g agrep with -2, but of course 2 is unknown). -Dc each deletion counts as c errors; c must be a nonnegative integer; the default value of c is 1 -Ic each insertion counts as c errors; c must be a nonnegative integer; the default value of c is 1 -Sc each substitution counts as c er- rors; c must be a nonnegative inte- ger; the default value of c is 1

Examples of using agrep

a g r e p -1 -I2 -D2 555-1234 phone- list finds all numbers that differ from 555-1234 in at most one digit; setting the cost of insertions and deletions to 2 prevents them in this case. agrep -B -d '$$' Shmidth address- list finds all addresses (assuming the addresses are separated by a blank line) containing the best match to Shmidth.

agrep -d " F r o m ' 'breakdown;ar- panet' mail-file outputs all mail messages (the pattern '^From ' separates mail messages in a mail file) that con- tain breakdown and arpanet (the symbol ; stands for the Boolean AND). agrep -B -w otomaton/usr/dict/ words

finds the closest words in the dic- tionary to otomaton; the -w option forces the match to be against the whole word rather than a part of it. (The best match has two errors and there are two of them: au- tomaton and tomato.) agrep -d '$$' - 1 ' < w o r d l > < w o r d 2 > ' finds all p a r a g r a p h s that contain word 1 followed by word2 with at most one e r r o r in place of the blank between the words (the < > indicate that no e r r o r is allowed inside). In particular, if w o r d l is the last word in a line and word is the first word in the next line, then the space will be substituted by a new line symbol and it will match. Thus, this is a way to overcome separation by a new line. Note that -d '$$' (or another delim that spans more than one line) is necessary, because other- wise agrep searches only one line at a time. agrep -5 ' a # b # c # d # e # f # g # h # i # j ' /usr/dict/words finds all words that have at least 5 of the first 10 letters of the alpha- bet in order; the # sign signals unlimited wild cards, which means here that any insertion is for free (there is actually a special option -p for that purpose). Try it; the answer starts with academia and ends with sacrilegious, which must mean something.

Conclusions

Searching text in the presence of errors is commonly done by h a n d - - one tries all possibilities. This is frustrating, slow, and with no guar- antee of success. T h e new algo- rithm presented in this article for searching with errors can alleviate this problem and make searching in general m o r e robust. It also makes searching more convenient by not having to spell everything precisely. T h e algorithm is very fast and gen- eral and it should find n u m e r o u s applications. T h e r e is one i m p o r t a n t area of searching with errors that we did not a d d r e s s - - s e a r c h i n g an indexed file. T h r o u g h o u t the article we as-

sumed that the files are not indexed (preprocessed) in any way, thus a sequential scan t h r o u g h them is necessary. We believe that the prob- lem of finding good indexing schemes that allow a p p r o x i m a t e search is the unresolved problem in this area. We note, however, that with the speed of c u r r e n t comput- ers, scanning large files (up to tens of MB) can be done reasonably fast. One can argue that since the size of o u r data increases as our speed o f processing it increases, waiting for faster computers will not help and indexing will always be necessary. This is certainly true for some ap- plications, but not for all. Some applications have a reasonable u p p e r b o u n d on their size and se- quential search for those applica- tions is (and will remain) realistic.

Acknowledgments We thank Ricardo Baeza-Yates, Gene Myers, and Chunghwa H. Rao for many helpful conversations about a p p r o x i m a t e string matching and for comments that improved the manuscript. We thank Ric An- derson, Cliff Hathaway, and Shu- I n g Tsuei for their help and com- ments that improved the imple- mentation o f agrep. We also thank William I. Chang for kindly provid- ing p r o g r a m s for some of the ex- periments. []

References

  1. Abrahamson, K. Generalized string matching. SIAM J. Comput. 16, 6 (1987), 1039-1051. 2. Baeza-Yates, R.A. and Gonnet, G.H. A new approach to text searching. Commun. ACM 35, 10 (1992). Preliminary version ap- peared in Proceedings of the 12th Annual ACM-SIGIR Conference on Information Retrieval, Cambridge, Mass. (June 1989), pp. 168-175.
  2. Boyer, R.S. and Moore, J.S. A fast string searching algorithm. Com- mun. ACM 20, 10 (Oct. 1977), 762-
  3. Chang, W.I. and Lawler, E.L. Ap- proximate string matching in sub- linear expected time. FOCS 90, pp. 116-124.
  4. Galil, Z. and Giancarlo, R. Data structures and algorithms for ap-

9 0 October 1992/Vol.35, No.10/COMMUNICATIONS OF THE ACM