首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >参数正则化

参数正则化
EN

Stack Overflow用户
提问于 2014-03-10 14:01:26
回答 3查看 82关注 0票数 0

我需要帮助为验证参数字符串创建regex。

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

因此,有效的字符串是:

代码语言:javascript
复制
P t
PO t
OZP ct
P tcmp
P
PZ
t
tp

等。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-03-10 14:24:45

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

代码语言:javascript
复制
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);
票数 1
EN

Stack Overflow用户

发布于 2014-03-10 14:15:09

为什么不放弃regex,使用string来表示非字符串数据?

代码语言:javascript
复制
[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

代码语言:javascript
复制
// equivalent to "PO mp", but checked at compile time.
YourMethod(First.P | First.O, Second.M | Second.P);

或者,如果你想

代码语言:javascript
复制
// same as above.
YourMethod((First)3, (Second)12);

如果您想知道更多关于这是如何工作的see this question

票数 2
EN

Stack Overflow用户

发布于 2014-03-10 14:20:42

这应该能满足你的需要:

代码语言:javascript
复制
([POZ]+)? ?([tcpm]+)?
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22302290

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档