in reply to Finding a partial match

G'day jpys,

This does what you asked for:

#!/usr/bin/env perl use strict; use warnings; my $string = '2cat6'; my @chars = split //, $string; my @tests = qw{2cat6 cat catch vwxyz 12345 67890 13457}; TEST: for my $test (@tests) { for my $char (@chars) { if (0 <= index $test, $char) { print "$test: true\n"; next TEST; } } print "$test: false\n"; }

Output:

2cat6: true cat: true catch: true vwxyz: false 12345: true 67890: true 13457: false

— Ken

Replies are listed 'Best First'.
Re^2: Finding a partial match
by hv (Prior) on May 07, 2023 at 13:11 UTC

    This does what you asked for

    It does what the OP appears to ask for, but probably in more extreme form than they want - the actual problem they are trying to solve is that "Sometimes when the string is created some bad words are formed and I want to avoid that". So if they test against a list of bad words, this will reject any string sharing even a single character with any of the bad words - potentially rejecting absolutely every string, if the list of bad words is extensive enough.

    For this context, one possibility (and one I would guess at) is that the OP wants to match not every length-1 substring of the bad words, but only those substrings that look close enough to the word that they bring it to mind. Assume "LACK" is a bad word: we might think that "LAC" and "LAK" are both close enough to bring it to mind, but that "ACK" is not. In that case a better solution might be to put "LAC" and "LAK" in the naughty list and reject only complete matches.

    At this stage, the OP is best served by helping them find the right questions to ask to clarify their own thoughts about what they want to achieve.

      I rather suspected that the OP would come back with additions to his spec: perhaps a minimum substring length; perhaps something else. Of course, he might simply adapt my code to count three consecutive matched characters, or whatever else he might want. I believed I was clear when I wrote: "This does what you asked for"; but maybe not.

      I did note the penultimate sentence about "bad words". It seemed to have no bearing on the relatively lengthy problem description which preceded it. It certainly didn't strike me as the "actual problem".

      Anyway, that's an interesting take; let's wait to see what the OP says.

      — Ken