Is there a way regex will match all the combinations of the tokens in `|` operator

拥有回忆 提交于 2021-02-10 19:21:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!