简体   繁体   English

参数正则表达式

[英]Parameter regex

I need help with creating regex for validating parameter string. 我需要帮助创建用于验证参数字符串的正则表达式。

Parameter string consists of 2 optional groups of explicit characters. 参数字符串由2个可选的显式字符组组成。 First group can contain only one occurrence of P, O, Z characters (order doesn't matter). 第一组只能包含一个P,O,Z字符(顺序无关紧要)。 Second group has same restrictions but can contain only characters t, c, p, m. 第二组具有相同的限制,但只能包含字符t,c,p,m。 If both groups are presented, they need to be delimited by a single space character. 如果呈现两个组,则需要用单个空格字符分隔。

So valid strings are: 所以有效的字符串是:

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

etc. 等等

Why not ditch regex, and using string to represent non string data, and do 为什么不抛弃正则表达式,并使用字符串来表示非字符串数据,并且这样做

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

You could then call YourMethod like this. 然后你可以像这样调用YourMethod

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

or, if you felt like it 或者,如果你觉得这样

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

If you'd like to know more about how this works see this question . 如果您想了解更多有关其工作原理的信息, 请参阅此问题

I don't think a regex is a good solution here, because it will have to be quite complicated: 我不认为正则表达式在这里是一个很好的解决方案,因为它必须非常复杂:

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

这应该给你你需要的东西:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM