blib/lib/String/FuzzyMatch.pm

filter: Statementstmt 100% 74 / 74 Branchbran 95.8% 23 / 24 Conditioncond 70.0% 35 / 50 MC/DCmcdc 56.0% 14 / 25 Subroutinesub 100% 13 / 13 Podpod 100% 2 / 2 totaltotal 85.6% 161 / 188 CC 32 SCAR 25.4
CC
32
Cov
89%
highlight
22.6
__ANON__
7.0
_naive_filter
4.1
CRAP 12.7
↑ Summary
1 package String::FuzzyMatch 0.01;
2 2 ▶use 5.022;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 2 ▶use experimental 'signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use feature 'postderef';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use Unicode::Normalize;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use Moo 2;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 =encoding utf8
9  
10 =head1 NAME
11  
12 String::FuzzyMatch - match strings fuzzily
13  
14 =head1 SYNOPSIS
15  
16 my $filter = String::FuzzyFind->new(
17 highlight_start => '[',
18 highlight_end => ']',
19 );
20  
21 $filter->filter( 'ab', ['aab','abc','acb','cba','aaa', 'abab'] );
22 # ['aab','abc','acb','abab' ]
23  
24 # By default ignores diacritics and case in haystack
25 $filter->( 'ab', ['Aäb','abc','Äbc','äcb','cba','aaa'] );
26 # ['Aäb','abc','Äbc','äcb' ]
27  
28 # By default respects diacritics in needle
29 $filter->( 'äb', ['aäb','abc','Äbc','äcb','cba','aaa'] );
30 # ['aäb','Äbc','äcb' ]
31  
32 # Ignore diacritics in needle as well
33 my $ignore_diacritics = String::FuzzyFind->new(
34 ignore_diacritics_lhs => 1,
35 );
36 $ignore_diacritics->( 'äb', ['aäb','abc','äbc','Äcb','cba','aaa'] );
37 # ['aäb','abc','äbc','Äcb']
38  
39  
40 $filter->highlight( 'ab', 'äcb' );
41 # '[ä]c[b]'
42  
43 $filter->highlight( 'ab', 'äb/c' );
44 # '[äb]/c'
45  
46 # HTML highlighting
47 my $html = String::FuzzyFind->new(
48 highlight_start => '<highlight>',
49 highlight_end => '</highlight>',
50 );
51 $html->highlight( 'ab', 'äcb' );
52 # '<highlight>ä</highlight>c<highlight>b</highlight>'
53  
54  
55 =head1 DESCRIPTION
56  
57 This module fuzzily matches strings. All characters of the search string
58 ("needle") must occur in sequence in the strings in the search list
59 ("haystack"). So filtering by C<ab> will find C<a/b>, C<aaaab>
60 and C<cranberry>.
61  
62 The searcher expects Unicode strings and matches using Unicode semantics.
63 The filter by default ignores diacritics and case in the haystack
64 and case in the needle, searching for C<abba> will also find C<ÄBBA>
65 by default.
66  
67 This search approach is heavily inspired by the
68 filtering in L<fzf|https://junegunn.github.io/fzf/> but does not
69 implement any of the advanced query language.
70  
71 =cut
72  
73 =head2 C<< new >>
74  
75 Creates a new filter
76  
77 my $filter = String::FuzzyFilter->new();
78  
79 =over 4
80  
81 =cut
82  
83 2 has '_filter_code' => (
84 is => 'ro',
85 required => 1,
86 );
87  
88 =item B<highlight>, B<highlight_start>, B<highlight_end>
89  
90 highlight => '_'
91  
92 String to use for highlighting. Default C<[> and C<]>.
93  
94 =cut
95 2 has 'highlight_start' => (
96 is => 'rw',
97 );
98  
99 2 has 'highlight_end' => (
100 is => 'rw',
101 );
102  
103 =item B<highlight_cb>
104  
105 highlight_cb => sub( $match ) { return "->$match<-" }
106  
107 Callback to return a highlighted match.
108 Default: C<undef>.
109  
110 =cut
111  
112 2 has 'highlight_cb' => (
113 is => 'rw',
114 );
115  
116 =item B<match>
117  
118 match => 'caption'
119  
120 Key of the hash to use for matching, if haystack contains only hashrefs. Can
121 be a scalar or a callback. Default: C<undef>.
122  
123 =back
124  
125 =cut
126  
127 2 has 'match' => (
128 is => 'ro',
129 );
130  
131 74 ▶sub _build_filter_re( $self, $needle, %args ) {
Subroutine _build_filter_re: called CC=3 SCAR=11.0
132 74 my $nfd_needle = NFD($needle);
133 74 my $q;
134  
135 74 ▶ if( !$args{ ignore_diacritics_lhs } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $args{'ignore_diacritics_lhs'}) { } 62 12 74
136 $q = '(?i)(.*?)' . join( '(.*?)',
137 117 map { "($_)" }
138 62 ▶ map { /\p{GrExt}/ ? quotemeta($_) : quotemeta($_) . '[\p{GrExt}]*\b{gcb}' }
Branch: 1 branch
BranchTrueFalseTotal
/\p{GrExt}/u ? : 10 107 117
139 split /\b{gcb}/, $nfd_needle )
140 . '(.*?)';
141  
142 } else {
143 12 $nfd_needle =~ s/\p{GrExt}//g;
144 $q = '(?i)(.*?)' . join( '(.*?)',
145 32 map { "($_)" }
146 12 map { quotemeta($_) } split /\b{gcb}/, $nfd_needle)
147 . '(.*?)';
148 }
149  
150 74 return $q;
151 }
152  
153 # Default filter builder
154 6 ▶sub _naive_filter( $self, %args ) {
Subroutine _naive_filter: called CC=4 SCAR=14.0
155 6 ▶ my $fetch = $args{ match } // (ref $self && $self->match);
Condition50%3/6
$args{"match"} // ref $self && $self->match
l!l&&r!l&&!r
240
ref $self and $self->match
!ll&&!rl&&r
400
MC/DC33%1/3
$args{"match"} // ref $self && $self->match
$args{"match"} ref $self $self->match
Truth table50%2/4
A // B and C
A= $args{"match"}B= ref $selfC= $self->match
ABCresult
1XX1
0111
00X0
0100
156  
157 6 ▶ if( $fetch ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fetch) { } 2 4 6
158 2 ▶ return sub( $needle, $haystack ) {
Subroutine __ANON__: called CC=1 SCAR=0.0
159 2 my $q = $self->_build_filter_re( $needle, %args );
160 return [
161 2 grep { NFD($fetch->($_)) =~ /$q/ }
162 $haystack->@*
163 ];
164 }
165  
166 2 } else {
167 24 ▶ return sub( $needle, $haystack ) {
Subroutine __ANON__: called CC=1 SCAR=0.0
168 24 my $q = $self->_build_filter_re( $needle, %args );
169 return [
170 24 grep { NFD($_) =~ /$q/ }
171 $haystack->@*
172 ];
173 }
174 4 };
175 }
176  
177  
178 # If you're looking here, you likely want to make the filter faster.
179 # The below versions are specialized versions of the _naive_filter()
180 # which I discarded, since the simplicity of the code was worth more to me
181 # than the potential performance
182 #sub _filter( $self, %args ) {
183 # my $transliterator = Text::Transliterator::Unaccent->new();
184 #
185 # return sub( $needle, $haystack ) {
186 # my $nfd_needle = NFD($needle);
187 # my $has_diacritics = ($nfd_needle =~ /\P{GrBase}/);
188 #
189 # if( $has_diacritics ) {
190 # my $diacritic_respecting = '(.*?)' . join( '(.*?)',
191 # map { /\p{GrExt}/ ? quotemeta($_) : quotemeta($_) . '[\p{GrExt}]*' }
192 # split /\b{gcb}/, $nfd_needle )
193 # . '(.*?)';
194 #
195 # return [
196 # grep { NFD($_) =~ /$diacritic_respecting/ }
197 # $haystack->@*
198 # ];
199 #
200 # } else {
201 # my $q = '(.*?)' . join( '(.*?)', map { quotemeta($_) } split //, $needle) . '(.*?)';
202 # return [
203 # grep { my $copy = $_; $transliterator->($copy); $copy =~ /$q/ }
204 # $haystack->@*
205 # ];
206 # }
207 # }
208 #}
209 #
210 ## ASCII filter builder, ignores diacritics on the lhs too
211 #sub _ascii_filter( $self, %args ) {
212 # # remove diacritics on the rhs
213 # # remove diacritics on the lhs
214 #
215 # my $transliterator = Text::Transliterator::Unaccent->new();
216 #
217 # return sub( $needle, $haystack ) {
218 # $transliterator->($needle);
219 # my $q = '(.*?)' . join( '(.*?)', map { quotemeta($_) } split //, $needle) . '(.*?)';
220 # return [
221 # grep { my $copy = $_; $transliterator->($copy); $copy =~ /$q/ }
222 # $haystack->@*
223 # ]
224 # }
225 #}
226  
227 6 ▶around BUILDARGS => sub( $orig, $class, %args ) {
Subroutine __ANON__: called CC=7 SCAR=19.5
228 6 ▶ if( $args{ match } && !ref $args{ match }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"match"} and not ref $args{"match"}) 1 5 6
Condition100%3/3
$args{"match"} and not ref $args{"match"}
!ll&&!rl&&r
411
MC/DC100%2/2
$args{"match"} and not ref $args{"match"}
$args{"match"} not ref $args{"match"}
Truth table100%3/3
A and not(B)
A= $args{"match"}B= not ref $args{"match"}
ABresult
0X0
100
111
229 1 my $key = delete $args{ match };
230 1 ▶ $args{ match } = sub( $o ) { $o->{$key} };
Subroutine __ANON__: called CC=1 SCAR=0.0
231 }
232  
233 6 $args{ _filter_code } = $class->_naive_filter( %args );
234  
235 #if( $args{ignore_diacritics_lhs} ) {
236 # $args{ _filter_code } = $class->_ascii_filter( %args );
237 #
238 #} else {
239 # $args{ _filter_code } = $class->_filter( %args );
240 #};
241  
242 6 ▶ $args{ highlight_start } //= $args{ highlight } // "[";
Condition75%3/4
$args{"highlight_start"} //= $args{"highlight"} // "["
l!l
15
$args{"highlight"} // "["
l!l
05
MC/DC100%1/1
$args{"highlight_start"} //= $args{"highlight"} // "["
$args{"highlight_start"}
Truth table100%2/2
A
A= $args{"highlight_start"}
Aresult
11
00
243 6 ▶ $args{ highlight_end } //= $args{ highlight } // "]";
Condition75%3/4
$args{"highlight_end"} //= $args{"highlight"} // "]"
l!l
15
$args{"highlight"} // "]"
l!l
05
MC/DC100%1/1
$args{"highlight_end"} //= $args{"highlight"} // "]"
$args{"highlight_end"}
Truth table100%2/2
A
A= $args{"highlight_end"}
Aresult
11
00
244  
245 6 return $class->$orig(%args);
246 2 };
247  
248 =head2 C<< ->filter $needle, $haystack >>
249  
250 my $results = $filter->filter( 'ab', ['ABBA','cabbage','all/users/ben','Änderungen (bearbeitet)','nobody'] );
251 # ['ABBA','cabbage','all/users/ben','Änderungen (bearbeitet)']
252  
253 Filters a list by the query given as string. All strings are assumed
254 to be Unicode strings.
255  
256 =cut
257  
258 26 ▶sub filter( $self, $needle, $haystack ) {
Subroutine filter: called CC=1 SCAR=0.0
Pod documented
259 26 $self->_filter_code->($needle,$haystack)
260 }
261  
262 =head2 C<< ->highlight $needle, $str >>
263  
264 Returns a string with the matched parts of a string highlighted.
265  
266 my $higlighted = $filter->highlight( 'ab', 'all/users/ben' );
267 # '[a]ll/users/[b]en'
268  
269 Note that the returned string will be in NFD.
270  
271 =cut
272  
273 48 ▶sub highlight( $self, $needle, $o_str, %args ) {
Subroutine highlight: called CC=21 SCAR=31.2
Pod documented
274 48 ▶ return $o_str unless length $needle;
Branch: 1 branch
BranchTrueFalseTotal
unless length $needle 0 48 48
275  
276 48 ▶ $args{ highlight_start } //= $self->highlight_start // $args{ highlight };
Condition33%2/6
$args{"highlight_start"} //= $self->highlight_start // $args{"highlight"}
l!l&&r!l&&!r
0480
$self->highlight_start // $args{"highlight"}
l!l&&r!l&&!r
4800
MC/DC0%0/3
$args{"highlight_start"} //= $self->highlight_start // $args{"highlight"}
$args{"highlight_start"} $self->highlight_start $args{"highlight"}
Truth table0%0/4
A //= B // C
A= $args{"highlight_start"}B= $self->highlight_startC= $args{"highlight"}
ABCresult
1XX1
01X1
0011
0000
277 48 ▶ $args{ highlight_end } //= $self->highlight_end // $args{ highlight };
Condition33%2/6
$args{"highlight_end"} //= $self->highlight_end // $args{"highlight"}
l!l&&r!l&&!r
0480
$self->highlight_end // $args{"highlight"}
l!l&&r!l&&!r
4800
MC/DC0%0/3
$args{"highlight_end"} //= $self->highlight_end // $args{"highlight"}
$args{"highlight_end"} $self->highlight_end $args{"highlight"}
Truth table0%0/4
A //= B // C
A= $args{"highlight_end"}B= $self->highlight_endC= $args{"highlight"}
ABCresult
1XX1
01X1
0011
0000
278 48 ▶ my $cb = $args{ highlight_cb } // $self->highlight_cb;
Condition66%2/3
$args{"highlight_cb"} // $self->highlight_cb
l!l&&r!l&&!r
01632
MC/DC50%1/2
$args{"highlight_cb"} // $self->highlight_cb
$args{"highlight_cb"} $self->highlight_cb
Truth table66%2/3
A // B
A= $args{"highlight_cb"}B= $self->highlight_cb
ABresult
1X1
011
000
279  
280 # Should match the other query-to-regex part
281 48 my $q = $self->_build_filter_re( $needle );
282  
283 48 my $str = NFD($o_str);
284  
285 48 ▶ $str =~ /$q/
Branch: 1 branch
BranchTrueFalseTotal
$str =~ /$q/u or return $o_str 45 3 48
286 or return $o_str;
287  
288 # Rebuild the string with the markers inserted
289 45 my $res = '';
290  
291 45 my ($match_start);
292  
293 45 for my $i (1.. scalar(@+) -1) {
294 213 my $matched = !($i % 2); # odd parentheses are matched parts
295  
296 #say sprintf "%02d: [%s] '%s'", $i, $matched ? 'x' : '-', substr( $str, $-[$i], $+[$i]-$-[$i] );
297 #use Data::Dumper; $Data::Dumper::Useqq = 1;
298 #say Dumper substr( $str, $-[$i], $+[$i]-$-[$i] );
299  
300 213 ▶ if( $matched and ($-[$i]==0 or $-[$i-1] != $+[$i-1])) {
Branch: 1 branch
BranchTrueFalseTotal
if ($matched and $-[$i] == 0 || $-[$i - 1] != $+[$i - 1]) 63 150 213
Condition100%6/6
$matched and $-[$i] == 0 || $-[$i - 1] != $+[$i - 1]
!ll&&!rl&&r
1292163
$-[$i] == 0 or $-[$i - 1] != $+[$i - 1]
l!l&&r!l&&!r
243921
MC/DC100%3/3
$matched and $-[$i] == 0 || $-[$i - 1] != $+[$i - 1]
$matched $-[$i] == 0 $-[$i - 1] != $+[$i - 1]
Truth table100%4/4
A and B or C
A= $matchedB= $-[$i] == 0C= $-[$i - 1] != $+[$i - 1]
ABCresult
0XX0
1000
11X1
1011
301 # A match just started
302 63 ▶ if( ! $cb ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cb) 42 21 63
303 42 $res .= $args{ highlight_start };
304 };
305 63 ▶ $match_start //= $-[$i];
Condition66%2/3
$match_start //= $-[$i]
l!l&&r!l&&!r
12510
MC/DC0%0/2
$match_start //= $-[$i]
$match_start $-[$i]
Truth table66%2/3
A //= B
A= $match_startB= $-[$i]
ABresult
1X1
011
000
306 };
307 213 ▶ if( !$matched and $-[$i] < $+[$i] and $i > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $matched and $-[$i] < $+[$i] and $i > 1) 18 195 213
Condition100%6/6
not $matched and $-[$i] < $+[$i] and $i > 1
!ll&&!rl&&r
1742118
not $matched and $-[$i] < $+[$i]
!ll&&!rl&&r
849039
MC/DC100%3/3
not $matched and $-[$i] < $+[$i] and $i > 1
not $matched $-[$i] < $+[$i] $i > 1
Truth table100%4/4
not(A) and B and C
A= not $matchedB= $-[$i] < $+[$i]C= $i > 1
ABCresult
0XX0
10X0
1100
1111
308 # A match just ended
309 18 ▶ if( $cb ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cb) { } 6 12 18
310 6 $res .= $cb->(substr( $str, $match_start, $+[$i-1]-$match_start ));
311 6 undef $match_start;
312 } else {
313 12 $res .= $args{ highlight_end };
314 };
315 };
316  
317 213 ▶ $res .= substr( $str, $-[$i], $+[$i]-$-[$i] )
Branch: 1 branch
BranchTrueFalseTotal
unless $matched and $cb 185 28 213
Condition100%3/3
$matched and $cb
!ll&&!rl&&r
1295628
MC/DC100%2/2
$matched and $cb
$matched $cb
Truth table100%3/3
A and B
A= $matchedB= $cb
ABresult
0X0
100
111
318 if( !$matched or !$cb);
319 }
320  
321 # Append the end, which is always unmatched
322 45 ▶ $res .= ($cb ? $cb->(substr( $str, $match_start, $+[scalar @+ -1]-$match_start )) : $args{ highlight_end }) . substr( $str, $+[-1] );
Branch: 1 branch
BranchTrueFalseTotal
$cb ? : 15 30 45
323  
324 45 return $res;
325 }
326  
327 2 1;
328  
329 =head1 REPOSITORY
330  
331 The public repository of this module is
332 L<https://github.com/Corion/String-FuzzyMatch>.
333  
334 =head1 SUPPORT
335  
336 The public support forum of this module is L<https://perlmonks.org/>.
337  
338 =head1 BUG TRACKER
339  
340 Please report bugs in this module via the Github bug queue at
341 L<https://github.com/Corion/String-FuzzyMatch/issues>
342  
343 =head1 AUTHOR
344  
345 Max Maischein C<corion@cpan.org>
346  
347 =head1 COPYRIGHT (c)
348  
349 Copyright 2026-2026 by Max Maischein C<corion@cpan.org>.
350  
351 =head1 LICENSE
352  
353 This module is released under the same terms as Perl itself.
354  
355 =cut
↑ Summary