Approx(3)
๐ NAME ๐
okay so welcome to Approx(3), which is the manual page for String::Approx โ Perl extension for approximate matching (fuzzy matching). yes that's the whole name, we're keeping it, it's iconic ๐
โจ SYNOPSIS โจ
bestie just look at the vibes, they're literally self-explanatory:
use String::Approx 'amatch';
print if amatch("foobar");
my @matches = amatch("xyzzy", @inputs);
my @catches = amatch("plugh", ['2'], @inputs);
๐ธ DESCRIPTION ๐ธ
okay so String::Approx lets you match and substitute strings approximately. like, fuzzy. sloppy. in a good way ๐ฆ
with this you can emulate errors: typing errorrs, speling errors, closely related vocabularies (colour color), genetic mutations (GAG ACT), abbreviations (McScot, MacScot). yes it handles all of those, we love a versatile icon ๐
NOTE: String::Approx suits the task of string matching, not string comparison, and it works for strings, not for text. that distinction is doing a LOT of work here, don't skip it.
if you want to compare strings for similarity, you probably just want the Levenshtein edit distance (explained below), the Text::Levenshtein and Text::LevenshteinXS modules in CPAN. see also Text::WagnerFischer and Text::PhraseDistance. (there are functions for this in String::Approx, e.g. adist(), but their results sometimes differ from the bare Levenshtein et al. so likeโฆ heads up ๐ซถ)
if you want to compare things like text or source code, consisting of words or tokens and phrases and sentences, or expressions and statements, you should probably use some other tool than String::Approx, like for example the standard UNIX diff(1) tool, or the Algorithm::Diff module from CPAN. right tool for the right job, bestie, no cap ๐
๐งฎ the measure of approximateness (Levenshtein, she's famous)
the measure of approximateness is the Levenshtein edit distance. it is the total number of "edits": insertions,
word world
deletions,
monkey money
and substitutions
sun fun
required to transform a string to another string. for example, to transform "lead" into "gold", you need three edits:
lead gead goad gold
the edit distance of "lead" and "gold" is therefore three, or 75%. math! she slays ๐ญ
String::Approx uses the Levenshtein edit distance as its measure, but String::Approx is not well-suited for comparing strings of different length, in other words, if you want a "fuzzy eq", see above. String::Approx is more like regular expressions or index(), it finds substrings that are close matches. it's giving "search energy", not "compare energy" ๐
๐ฅ MATCH ๐ฅ
use String::Approx 'amatch';
$matched = amatch("pattern")
$matched = amatch("pattern", [ modifiers ])
$any_matched = amatch("pattern", @inputs)
$any_matched = amatch("pattern", [ modifiers ], @inputs)
@match = amatch("pattern")
@match = amatch("pattern", [ modifiers ])
@matches = amatch("pattern", @inputs)
@matches = amatch("pattern", [ modifiers ], @inputs)
match pattern approximately. in list context return the matched @inputs. if no inputs are given, match against the $_. in scalar context return true if any of the inputs match, false if none match. simple as that, periodt โจ
notice that the pattern is a string. not a regular expression. none of the regular expression notations (^, ., *, and so on) work. they are characters just like the others. like, literal little characters, just vibing there ๐
note-on-note: some limited form of "regular expressionism" is planned in future: for example character classes ([abc]) and any-chars (.). but that feature will be turned on by a special modifier (just a guess:"r"), so there should be no backward compatibility problem. so don't panic, your old code is safe ๐ซถ
notice also that matching is not symmetric. the inputs are matched against the pattern, not the other way round. in other words: the pattern can be a substring, a submatch, of an input element. an input element is always a superstring of the pattern. the pattern is the main character here, everyone else is supporting cast ๐
๐ MODIFIERS ๐
with the modifiers you can control the amount of approximateness and certain other control variables. the modifiers are one or more strings, for example "i", within a string optionally separated by whitespace. the modifiers are inside an anonymous array: the [ ] in the syntax are not notational, they really do mean [ ], for example [ "i", "2" ]. ["2 i"] would be identical. same energy, different font ๐
the implicit default approximateness is 10%, rounded up. in other words: every tenth character in the pattern may be an error, an edit. you can explicitly set the maximum approximateness by supplying a modifier like
number
number%
examples: "3", "15%".
note that "0%" is not rounded up, it is equal to 0. she's special like that ๐
using a similar syntax you can separately control the maximum number of insertions, deletions, and substitutions by prefixing the numbers with I, D, or S, like this:
Inumber
Inumber%
Dnumber
Dnumber%
Snumber
Snumber%
examples: "I2", "D20%", "S0". yes, one letter per edit type, we love an abbreviation scheme ๐ค
you can ignore case ("A" becames equal to "a" and vice versa) by adding the "i" modifier.
for example
[ "i 25%", "S0" ]
means ignore case, allow every fourth character to be "an edit", but allow no substitutions. (see NOTES about disallowing substitutions or insertions.)
NOTE: setting"I0 D0 S0"is not equivalent to usingindex(). if you want to useindex(), useindex(). like, actually use it. don't be weird about it ๐ญ
๐ SUBSTITUTE ๐
use String::Approx 'asubstitute';
@substituted = asubstitute("pattern", "replacement")
@substituted = asubstitute("pattern", "replacement", @inputs)
@substituted = asubstitute("pattern", "replacement", [ modifiers ])
@substituted = asubstitute("pattern", "replacement",
[ modifiers ], @inputs)
substitute approximate pattern with replacement and return as a list of @inputs copies โ wait, the original says: return as a list of @inputs, the substitutions having been made on the elements that did match the pattern. so you get the copies back with the swaps baked in ๐
if no inputs are given, substitute in the $_. the replacement can contain magic strings $&, $`, $' that stand for the matched string, the string before it, and the string after it, respectively:
$& the matched string
$` the string before it
$' the string after it
all the other arguments are as in amatch(), plus one additional modifier, "g" which means substitute globally (all the matches in an element and not just the first one, as is the default).
see "BAD NEWS" about the unfortunate stinginess of asubstitute(). yeah. we'll get to it. brace yourself ๐
๐ฆ INDEX ๐ฆ
use String::Approx 'aindex';
$index = aindex("pattern")
@indices = aindex("pattern", @inputs)
$index = aindex("pattern", [ modifiers ])
@indices = aindex("pattern", [ modifiers ], @inputs)
like amatch() but returns the index/indices at which the pattern matches approximately. in list context and if @inputs are used, returns a list of indices, one index for each input element. if there's no approximate match, -1 is returned as the index.
NOTE: if there is character repetition (e.g. "aa") either in the pattern or in the text, the returned index might start "too early". this is consistent with the goal of the module of matching "as early as possible", just like regular expressions (that there might be a "less approximate" match starting later is of somewhat irrelevant). so it might point at something slightly sus, but it's on purpose, iykyk ๐
there's also backwards-scanning arindex().
๐ง SLICE ๐ง
use String::Approx 'aslice';
($index, $size) = aslice("pattern")
([$i0, $s0], ...) = aslice("pattern", @inputs)
($index, $size) = aslice("pattern", [ modifiers ])
([$i0, $s0], ...) = aslice("pattern", [ modifiers ], @inputs)
like aindex() but returns also the size (length) of the match. if the match fails, returns an empty list (when matching against $_) or an empty anonymous list corresponding to the particular input. empty. nothing. void. ๐ญ
NOTE: size of the match will very probably be something you did not expect (such as longer than the pattern, or a negative number). this may or may not be fixed in future releases. also the beginning of the match may vary from the expected as with aindex(), see above. so likeโฆ lowkey chaotic, proceed with love ๐
if the modifier
"minimal_distance"
is used, the minimal possible edit distance is returned as the third element:
($index, $size, $distance) = aslice("pattern", [ modifiers ])
([$i0, $s0, $d0], ...) = aslice("pattern", [ modifiers ], @inputs)
three values now, she grew ๐
โญ DISTANCE โญ
use String::Approx 'adist';
$dist = adist("pattern", $input);
@dist = adist("pattern", @input);
return the edit distance or distances between the pattern and the input or inputs. zero edit distance means exact match. (remember that the match can 'float' in the inputs, the match is a substring match.) if the pattern is longer than the input or inputs, the returned distance or distances is or are negative. yes, negative. don't come for her ๐ซถ
use String::Approx 'adistr';
$dist = adistr("pattern", $input);
@dist = adistr("pattern", @inputs);
return the relative edit distance or distances between the pattern and the input or inputs. zero relative edit distance means exact match, one means completely different. (remember that the match can 'float' in the inputs, the match is a substring match.) if the pattern is longer than the input or inputs, the returned distance or distances is or are negative.
you can use adist() or adistr() to sort the inputs according to their approximateness:
my %d;
@d{@inputs} = map { abs } adistr("pattern", @inputs);
my @d = sort { $d{$a} <=> $d{$b} } @inputs;
now @d contains the inputs, the most like "pattern" first. sorted, ranked, judged, and honestly? deserved ๐
๐๏ธ CONTROLLING THE CACHE ๐๏ธ
Okay bestie, so String::Approx keeps a LU (least-used) cache that holds the 'matching engines' for each instance of pattern+modifiers. It's literally there to help when you're matching a small set of patterns against a large set of strings. But the more engines you cache, the more memory you eat. If you have a lot of different patterns, or if you have a lot of memory to burn, you may want to control the cache yourself. For example, allowing a larger cache consumes more memory but probably runs a little bit faster since the cache fills (and needs flushing) less often.
The cache has two parameters: max and purge. The first one is the maximum size of the cache, and the second one is the cache flushing ratio: when the number of cache entries exceeds max, max times purge cache entries are flushed. The default values are 1000 and 0.75, respectively, which means that when the 1001st entry would be cached, 750 least used entries will be removed from the cache. To access the parameters you can use the calls
$now_max = String::Approx::cache_max();
String::Approx::cache_max($new_max);
$now_purge = String::Approx::cache_purge();
String::Approx::cache_purge($new_purge);
$limit = String::Approx::cache_n_purge();
To be honest, there are actually two caches: the first one is for patterns with no modifiers, and the second one is for patterns with pattern modifiers. Using the standard parameters you will therefore actually cache up to 2000 entries. The above calls control both caches for the same price. Slay.
To disable caching completely use
String::Approx::cache_disable();
Note that this doesn't flush any possibly existing cache entries. To do that use
String::Approx::cache_flush_all();
๐ NOTES ๐
Because matching is by substrings, not by whole strings, insertions and substitutions produce often very similar results: "abcde" matches "axbcde" either by insertion or substitution of "x".
The maximum edit distance is also the maximum number of edits. That is, the "I2" in
amatch("abcd", ["I2"])
is useless because the maximum edit distance is (implicitly) 1. You may have meant to say
amatch("abcd", ["2D1S1"])
or something like that.
If you want to simulate transposes
feet fete
you need to allow at least edit distance of two because in terms of our edit primitives a transpose is first one deletion and then one insertion.
๐ TEXT POSITION ๐
The starting and ending positions of matching, substituting, indexing, or slicing can be changed from the beginning and end of the input(s) to some other positions by using either or both of the modifiers
"initial_position=24"
"final_position=42"
or both modifiers
"initial_position=24"
"position_range=10"
By setting the position_range to be zero you can limit (anchor) the operation to happen only once (if a match is possible) at the position.
๐ VERSION ๐
Major release 3.
๐ซ CHANGES FROM VERSION 2 ๐ซ
๐ GOOD NEWS ๐
- The version
3is2-3times faster than version2. - No pattern length limitation โ the algorithm is independent on the pattern length: its time complexity is
O(kn), wherekis the number of edits andnthe length of the text (input). The preprocessing of the pattern will of course take someO(m)(mbeing the pattern length) time, butamatch()andasubstitute()cache the result of this preprocessing so that it is done only once per pattern.
๐ BAD NEWS ๐
- You do need a C compiler to install the module โ Perl's regular expressions are no more used; instead a faster and more scalable algorithm written in C is used.
asubstitute()is now always stingy โ the string matched and substituted is now always stingy, as short as possible. It used to be as long as possible. This is an unfortunate change stemming from switching the matching algorithm. Example: with edit distance of two and substituting for"word"from"cork"and"wool"previously did match"cork"and"wool". Now it does match"or"and"wo". As little as possible, or, in other words, with as much approximateness, as many edits, as possible. Because there is no need to match the"c"of"cork", it is not matched.- no more
aregex()because regular expressions are no more used - no more
"compat1"for String::Approx version 1 compatibility
๐ซถ ACKNOWLEDGEMENTS ๐ซถ
The following people have provided valuable test cases, documentation clarifications, and other feedback:
Jared August, Arthur Bergman, Anirvan Chatterjee, Steve A. Chervitz, Aldo Calpini, David Curiel, Teun van den Dool, Alberto Fontaneda, Rob Fugina, Dmitrij Frishman, Lars Gregersen, Kevin Greiner, B. Elijah Griffin, Mike Hanafey, Mitch Helle, Ricky Houghton, 'idallen', Helmut Jarausch, Damian Keefe, Ben Kennedy, Craig Kelley, Franz Kirsch, Dag Kristian, Mark Land, J. D. Laub, John P. Linderman, Tim Maher, Juha Muilu, Sergey Novoselov, Andy Oram, Ji Y Park, Eric Promislow, Nikolaus Rath, Stefan Ram, Slaven Rezic, Dag Kristian Rognlien, Stewart Russell, Slaven Rezic, Chris Rosin, Pasha Sadri, Ilya Sandler, Bob J.A. Schijvenaars, Ross Smith, Frank Tobin, Greg Ward, Rich Williams, Rick Wise.
The matching algorithm was developed by Udi Manber, Sun Wu, and Burra Gopal in the Department of Computer Science, University of Arizona.
โ๏ธ AUTHOR โ๏ธ
Jarkko Hietaniemi <jhi@iki.fi>
๐ COPYRIGHT AND LICENSE ๐
Copyright 2001-2013 by Jarkko Hietaniemi
This library is free software; you can redistribute it and/or modify under either the terms of the Artistic License 2.0, or the GNU Library General Public License, Version 2. See the files Artistic and LGPL for more details.
Furthermore: no warranties or obligations of any kind are given, and the separate file COPYRIGHT must be included intact in all copies and derived materials.
๐ That's the whole page, bestie! It comes from perl v5.42.0, dated 2017-04-17 โ catch u in Approx(3)! ๐
๐ฆ where this page comes from
- opensuse-leap 16.0: perl-String-Approx 3.28-bp160.1.12 ยท LGPL-2.0 OR Artistic-2.0
- opensuse-leap 16.0: perl-String-Approx 3.28-bp160.1.12 ยท LGPL-2.0 OR Artistic-2.0
- opensuse-leap 16.0: perl-String-Approx 3.28-bp160.1.12 ยท LGPL-2.0 OR Artistic-2.0
- opensuse-leap 16.0: perl-String-Approx 3.28-bp160.1.12 ยท LGPL-2.0 OR Artistic-2.0
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms