Regex with all optional parts but at least one required

前端 未结 4 592
我寻月下人不归
我寻月下人不归 2020-12-22 02:03

I need to write a regex that matches strings like \"abc\", \"ab\", \"ac\", \"bc\", \"a\", \"b\", \"c\". Order is important and it shouldn\'t match multiple appearances of th

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-22 02:11

    To do this with pure regex you're going to have to expand it into all of its possibilities:

    ab?c?|a?bc?|a?b?c
    

    If you have lookaheads you can make sure the string is non-empty. Or you can verify the string has a length of at least one before passing it to the expression, depending on your choice of language.

    For example a .NET lookahead might look like this:

    ^(?=[abc])a?b?c?$
    

    Or you could just test your string's length before matching it:

    if (YourString.Length == 1) {
       // matching code goes here, using the expression a?b?c?
    }
    

提交回复
热议问题