Home > OS >  perl regex: All must be present
perl regex: All must be present

Time:04-22

I'm writing a wordle assistant. Is there a regex format that says "match only if all these letters are present, in any order"? The character class syntax [abc] is an OR operation; I'm looking for the equivalent AND.

For example, "cranberry" would match /{abc}/, but "cranny", lacking a 'b', would not.

I'm aware of the answer of $word =~ /^(?=.*a)(?=.*b)(?=.*c)/, and also $_= $word; /a/ && /b/ && /c/, but I was wondering if there is anything more elegant.

CodePudding user response:

[abc] means the character must be a or b or c.

To match a character that is a and b and c, you can use the (?[ ... ]).[1]

(?[ [a] & [b] & [c] ])

But of course, you don't want AND. You want

(?: a.*b.*c
|   a.*c.*b
|   b.*a.*c
|   b.*c.*a
|   c.*a.*b
|   c.*b.*a
)

So /a/ && /b/ && /c/ is quite an elegant solution.


  1. It's an experimental feature, but one I predict will be accepted without change.

CodePudding user response:

If you want a and b and c in any order, you do:

$matches = ($word =~ /a/ && $word =~ /b/ && $word =~ /c/);
  • Related