Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 正则表达式验证,仅允许在与左括号匹配时使用右括号_C#_Regex - Fatal编程技术网

C# 正则表达式验证,仅允许在与左括号匹配时使用右括号

C# 正则表达式验证,仅允许在与左括号匹配时使用右括号,c#,regex,C#,Regex,说到正则表达式验证,我完全是个新手。我的目标是使用以下条件验证用户输入的字符串: 字符串可以用括号括起来,也可以不用括号括起来 只允许在字符串末尾使用右括号 只允许在字符串开头使用左括号 仅当结尾处有右括号时,才允许使用左括号 仅当字符串开头有一个左括号时,才允许使用右括号 下面是有效字符串的示例: anytexthere (anytexthere) (anytexthere anytexthere) any(texthere) (anytext)here any(texthere any)t

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

  • 字符串可以用括号括起来,也可以不用括号括起来
  • 只允许在字符串末尾使用右括号
  • 只允许在字符串开头使用左括号
  • 仅当结尾处有右括号时,才允许使用左括号
  • 仅当字符串开头有一个左括号时,才允许使用右括号
  • 下面是有效字符串的示例:

    anytexthere
    (anytexthere)
    
    (anytexthere
    anytexthere)
    any(texthere)
    (anytext)here
    any(texthere
    any)texthere
    any()texthere
    
    无效字符串:

    anytexthere
    (anytexthere)
    
    (anytexthere
    anytexthere)
    any(texthere)
    (anytext)here
    any(texthere
    any)texthere
    any()texthere
    
    任何帮助都将不胜感激。我真的开始怀疑,仅仅使用一个正则表达式是否就可以做到这一点

    谢谢:)

    您可以使用:

    当然,由于字符串只有两种匹配方式:

    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))