在正则表达式验证方面,我是一个新手。我的目标是使用以下条件验证用户输入的字符串:
以下是有效字符串的示例:
anytexthere
(anytexthere)
字符串无效:
(anytexthere
anytexthere)
any(texthere)
(anytext)here
any(texthere
any)texthere
any()texthere
非常感谢任何帮助。我真的开始怀疑只使用一个正则表达式是否可行。
谢谢:)
答案 0 :(得分:3)
您可以使用conditional:
来完成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))