问题
I am doing a parser for nand2tetris project. I want to check if the destination field is either M|D|MD|A|AM|AD|AMD
and their different ways of combinations like MA
not only AM
.
^(M|D|MD|A|AM|AD|AMD)\s*=$
This regex correctly matches AM=
, but not MA=
.
I don't want to list out all the possible combinations of those tokens, is there a way to do it simply?
回答1:
This should do it:
^(?=[MDA]+$)(?!.?(.).?\1).{1,3}$
Demo
The negative lookahead attempts to match two "M"
's, two "D"
's or two "A"
's.
The positive lookahead merely restricts the characters in the string to "M"
, "D"
and "A"
. That was not necessary but it allows me to use .
's in the rest, rather than (?![MDA]?([MDA])[MDA]?...)
, which may make it easier to read.
来源:https://stackoverflow.com/questions/60575231/is-there-a-way-regex-will-match-all-the-combinations-of-the-tokens-in-operat