C# 参数正则表达式

C# 参数正则表达式,c#,regex,C#,Regex,我需要帮助创建用于验证参数字符串的正则表达式 参数字符串由两组可选的显式字符组成。第一组只能包含一次出现的P、O、Z字符(顺序无关紧要)。第二组具有相同的限制,但只能包含字符t、c、p、m。如果两个组都显示,则需要用单个空格字符分隔 因此,有效字符串是: P t PO t OZP ct P tcmp P PZ t tp 等等。为什么不抛弃正则表达式,使用字符串表示非字符串数据,然后 [Flags] enum First { None = 0, P = 1, O = 2,

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

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

因此,有效字符串是:

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

等等。

为什么不抛弃正则表达式,使用字符串表示非字符串数据,然后

[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);


如果您想了解更多有关此操作的信息。

这将为您提供所需的:

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

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

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);
Regex regexObj=新的Regex(
@“^#字符串的开头
(?:#启动非捕获组:
([POZ])#匹配并捕获第1组中的[POZ]之一
(?![POZ]*\1)#断言该角色不会再次出现
)*#重复任意次数(包括零次)
(?:#启动另一个非捕获组:

(?这不太适合正则表达式。它必须是正则表达式吗?为什么?用户正在使用可选筛选参数(标志)调用服务)。第一组应按主类别筛选数据,第二组按子类别筛选数据。每个类别都指定了特殊字符。我只想确保用户提供的参数格式正确,以便我可以继续请求。您希望如何处理重复项,即
PPP ttttttt
,拒绝还是允许?@Jodrell:他希望o拒绝它们(“只能包含一次…”)。这与有效字符串匹配,但不能排除无效字符串。您应该在这里解释2的幂的用法。@LukeWillis,希望我有。我想投票表决,但无法在这里使用@Jodrell:对我有效-您是否检查了
IgnorePatternWhitespace
?如果我在Regex Hero使用
IgnorePatternWhit进行测试,效果会很好espace
多行