'perl regex: All must be present
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.
Solution 1:[1]
[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.
- It's an experimental feature, but one I predict will be accepted without change.
Solution 2:[2]
If you want a and b and c in any order, you do:
$matches = ($word =~ /a/ && $word =~ /b/ && $word =~ /c/);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ikegami |
| Solution 2 | Andy Lester |
