不按特定顺序匹配一个字符的正则表达式

Regex matchig one character in no particular order

我希望这个正则表达式条件为真:

  1. 字符串只有 1 或 2 个字符长
  2. 仅当字符串包含 'a' 或 'ab' 或 'ba' 或 'b'
  3. 时条件才为真

谢谢

ps:无效:

  1. '^[ab]{1,2}$'
  2. '^[^ab][ab][^ab]$'
  3. '^[^ab]([ab]{1,2})[^ab]$'

您可以使用您列举的模式:'a' or 'ab' or 'ba' or 'b'

^(?:a|ab|ba|b)$

这个带有非捕获组的表达式也可能有效:

^(?:ab?|ba?)$

或使用捕获组:

^(ab?|ba?)$

Demo


If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


正则表达式电路

jex.im 可视化正则表达式: