检查字符串是否是一堆字符的子集?(正则表达式)? [英] Check if string is subset of a bunch of characters? (RegEx)?
问题描述
我有一个小问题,我有8个字符,例如a b c d a e f g",还有一个单词列表,例如:妈妈,爸爸,坏,同性恋,abac
I have a little problem, I have 8 characters, for example "a b c d a e f g", and a list of words, for example: mom, dad, bad, fag, abac
我如何检查我是否可以用我拥有的字母组合这些单词?在我的例子中,我可以创作 bad、abac 和 fag,但我不能创作爸爸(我没有两个 D)和妈妈(我没有 M 或 O).
How can I check if I can or cannot compose these words with the letters I have? In my example, I can compose bad, abac and fag, but I cannot compose dad (I have not two D) and mom (I have not M or O).
我很确定它可以使用 RegEx 来完成,但即使使用 Perl 中的某些函数也会很有帮助.在此先感谢各位!:)
I'm pretty sure it can be done using a RegEx but would be helpful even using some functions in Perl.. Thanks in advance guys! :)
推荐答案
最简单的方法是将要测试的单词形成一个正则表达式.
This is done most simply by forming a regular expression from the word that is to be tested.
这对可用字符列表进行排序并通过连接它们形成一个字符串.然后将每个候选词拆分为字符、排序并使用正则表达式项 .*
作为分隔符重新连接.因此,例如,abac
将被转换为 a.*a.*b.*c
.
This sorts the list of available characters and forms a string by concatenating them. Then each candidate word is split into characters, sorted, and rejoined with the regex term .*
as separator. So, for instance, abac
will be converted to a.*a.*b.*c
.
然后通过根据派生的正则表达式测试可用字符串来确定单词的有效性.
Then the validity of the word is determined by testing the string of available characters against the derived regex.
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
这篇关于检查字符串是否是一堆字符的子集?(正则表达式)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!