参数正则表达式

时间:2014-03-10 14:01:27

标签: c# regex

我需要帮助创建用于验证参数字符串的正则表达式。

参数字符串由2个可选的显式字符组组成。第一组只能包含一个P,O,Z字符(顺序无关紧要)。第二组具有相同的限制,但只能包含字符t,c,p,m。如果呈现两个组,则需要用单个空格字符分隔。

所以有效的字符串是:

P t
PO t
OZP ct
P tcmp
P
PZ
t
tp

3 个答案:

答案 0 :(得分:2)

为什么不抛弃正则表达式,并使用字符串来表示非字符串数据,并执行

[Flags]
enum First
{
    None = 0,
    P = 1,
    O = 2,
    Z = 4
}

[Flags]
enum Second
{
    None = 0
    T = 1,
    C = 2,
    P = 4,
    M = 8
}

void YourMethod(First first, Second second)
{
    bool hasP = first.HasFlag(First.P);
    var hasT = second.HasFlag(Second.T);
}

然后你可以这样打电话给YourMethod

// equivalent to "PO mp", but checked at compile time.
YourMethod(First.P | First.O, Second.M | Second.P);

或者,如果你觉得这样的话

// same as above.
YourMethod((First)3, (Second)12);

如果您想了解更多有关其工作原理see this question

答案 1 :(得分:1)

我不认为正则表达式是一个很好的解决方案,因为它必须非常复杂:

Regex regexObj = new Regex(
    @"^               # Start of string
    (?:               # Start non-capturing group:
     ([POZ])          # Match and capture one of [POZ] in group 1
     (?![POZ]*\1)     # Assert that that character doesn't show up again
    )*                # Repeat any number of times (including zero)
    (?:               # Start another non-capturing group:
     (?<!^)           # Assert that we're not at the start of the string
     \                # Match a space
     (?!$)            # Assert that we're also not at the end of the string
    )?                # Make this group optional.
    (?<!              # Now assert that we're not right after...
     [POZ]            # one of [POZ] (i. e. make sure there's a space)
     (?!$)            # unless we're already at the end of the string.
    )                 # End of negative lookahead assertion
    (?:               # Start yet another non-capturing group:
     ([tcpm])         # Match and capture one of [tcpm] in group 2
     (?![tcpm]*\2)    # Assert that that character doesn't show up again
    )*                # Repeat any number of times (including zero)
    $                 # End of string", 
    RegexOptions.IgnorePatternWhitespace);

答案 2 :(得分:-1)

这应该可以满足您的需求:

([POZ]+)? ?([tcpm]+)?