正则表达式,带有所有可选部件,但至少需要一个 [英] Regex with all optional parts but at least one required
问题描述
我需要编写一个正则表达式来匹配诸如 abc, ab, ac, bc, a, b, c之类的字符串。顺序很重要,并且不应该与同一部分的多个外观匹配。
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 the same part.
a?b?c?几乎可以解决问题。除了它也匹配空字符串。有什么方法可以防止它匹配空字符串,或者有其他方法可以为任务编写正则表达式。
a?b?c? almost does the trick. Except it matches empty strings too. Is there any way to prevent it from matching empty strings or maybe a different way to write a regex for the task.
推荐答案
到使用纯正则表达式来做到这一点,您将不得不将其扩展到所有可能性:
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.
例如,.NET lookahead可能看起来像像这样:
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?
}
这篇关于正则表达式,带有所有可选部件,但至少需要一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!