[英]Parameter regex
我需要幫助創建用於驗證參數字符串的正則表達式。
參數字符串由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);
如果您想了解更多有關其工作原理的信息, 請參閱此問題 。
我不認為正則表達式在這里是一個很好的解決方案,因為它必須非常復雜:
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.