[英]Regex validation to only allow closing parenthesis when matched by an opening parenthesis
在涉及正則表達式驗證時,我是一個全新的人。 我的目標是使用以下條件驗證用戶輸入的字符串:
以下是有效字符串的示例:
anytexthere
(anytexthere)
無效的字符串:
(anytexthere
anytexthere)
any(texthere)
(anytext)here
any(texthere
any)texthere
any()texthere
任何幫助將不勝感激。 我真的開始懷疑只使用一個正則表達式是否可行。
謝謝 :)
你可以用條件 :
if (Regex.IsMatch(subject,
@"^ # Start of string
( # Match and capture into group 1:
\( # an opening parenthesis
)? # optionally.
[^()]* # Match any number of characters except parentheses
(?(1) # Match (but only if capturing group 1 participated in the match)
\) # a closing parenthesis.
) # End of conditional
$ # End of string",
RegexOptions.IgnorePatternWhitespace)) {
// Successful match
}
或者,當然,因為字符串只能匹配兩種方式:
if (Regex.IsMatch(subject,
@"^ # Start of string
(?: # Either match
\( # an opening parenthesis,
[^()]* # followed by any number of non-parenthesis characters
\) # and a closing parenthesis
| # or
[^()]* # match a string that consists only of non-parens characters
) # End of alternation
$ # End of string",
RegexOptions.IgnorePatternWhitespace))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.