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