1

在正则表达式验证方面,我完全是新手。我的目标是使用以下条件验证用户输入的字符串:

  1. 该字符串可能包含在括号中,也可能不包含在括号中。
  2. 右括号只允许在字符串的末尾。
  3. 只允许在字符串的开头使用左括号。
  4. 仅当末尾有右括号时才允许使用左括号。
  5. 仅当字符串开头有左括号时才允许使用右括号。

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

anytexthere
(anytexthere)

无效的字符串:

(anytexthere
anytexthere)
any(texthere)
(anytext)here
any(texthere
any)texthere
any()texthere

任何帮助将不胜感激。我真的开始怀疑这是否可能仅通过使用单个正则表达式来实现。

谢谢 :)

4

1 回答 1

3

你可以用一个条件来做到这一点:

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)) 
于 2013-05-30T15:07:28.383 回答