Check if a string is a subset of a bunch of characters? (RegEx)?

I have a little problem, I have 8 characters, for example "abcdaef g" and a list of words, for example: mom, dad, bad, fag, abac

How can I check if I can or cannot compose these words with the letters that I have? In my example, I can make bad, abac and fag, but I can not make dad (I don't have two D) and mom (I don't have M or O).

I'm sure this can be done with RegEx, but it would be useful to use some features in Perl. Thanks in advance guys! :)

+1
source share
6 answers

This is most easily done by forming a regular expression from a word that needs to be checked.

. - , regex .* . , , abac a.*a.*b.*c.

.

use strict;
use warnings;

my @chars = qw/ a b c d a e f g /;
my $chars = join '', sort @chars;

for my $word (qw/ mom dad bad fag abac /) {
  my $re = join '.*', sort $word =~ /./g;
  print "$word is ", $chars =~ /$re/ ? 'valid' : 'NOT valid', "\n";
}

mom is NOT valid
dad is NOT valid
bad is valid
fag is valid
abac is valid
+6

, . , .

, .

( Perl-!):

, ( ):

^

, :

(?!(?:[^<char>]*+<char>){<count + 1>})

: (?!(?:[^a]*+a){3}), a 2.

, (?!pattern). , , (?:[^a]*+a){3}. , , , 3 'a' . 3 'a', , 2 'a'.

, *+, 0 , . , .

, []:

[<unique_chars_in_list>]+

: a b c d a e f g [abcdefg]+. , .

, :

$

, , :

^(?!(?:[^a]*+a){3})(?!(?:[^b]*+b){2})(?!(?:[^c]*+c){2})(?!(?:[^d]*+d){2})(?!(?:[^e]*+e){2})(?!(?:[^f]*+f){2})(?!(?:[^g]*+g){2})[abcdefg]+$

i .

, (a-z) . () .

+2

, , . * :

'aabcdefg' =~ m/a.*b.*d.*/
True
'aabcdefg' =~ m/m.*m.*u.*/
False
'aabcdefg' =~ m/a.*d.*d.*/
False
+1

:

  • :

      • , . , .

, . . , , , , , .

0

script, :

#!/usr/bin/env perl

use strict;
use warnings;

sub check_word {
  my $word = shift;
  my %chars;
  $chars{$_}++ for @_;
  $chars{$_}-- or return for split //, $word;
  return 1;
}

print check_word( 'cab', qw/a b c/ ) ? "Good" : "Bad";

And, of course, the performance of this function can be significantly increased if the list of letters is the same every time. Actually for eight characters, copying a hash and creating a new one each time is probably equal to speed.

0
source

pseudo code:

bool possible=true
string[] chars= { "a", "b", "c"}   
foreach word in words
{
     foreach char in word.chars
     {
          possible=possible && chars.contains(char)
     }
}
-2
source

All Articles