簡體   English   中英

正則表達式驗證僅允許在用左括號匹配時關閉括號

[英]Regex validation to only allow closing parenthesis when matched by an opening parenthesis

在涉及正則表達式驗證時,我是一個全新的人。 我的目標是使用以下條件驗證用戶輸入的字符串:

  1. 字符串可以包含也可以不包含在括號中。
  2. 只允許在字符串的末尾使用右括號。
  3. 僅在字符串的開頭允許左括號。
  4. 只有在末尾有一個右括號時才允許使用左括號。
  5. 只有在字符串開頭有一個左括號時才允許使用右括號。

以下是有效字符串的示例:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM