我已经浏览了很多关于 SO 的帖子。我没有找到我的特定场景所需的内容。
我需要一个字母数字字符串的正则表达式。 其中应符合以下条件
有效字符串:
ameya123 (alphabets and numbers)
ameya (only alphabets)
AMeya12(Capital and normal alphabets and numbers)
Ameya_123 (alphabets and underscore and numbers)
Ameya_ 123 (alphabets underscore and white speces)
无效字符串:
123 (only numbers)
_ (only underscore)
(only space) (only white spaces)
any special charecter other than underscore
到目前为止我尝试了什么:
(?=.*[a-zA-Z])(?=.*[0-9]*[\s]*[_]*)
以上正则表达式在 Regex online editor 中有效但是在 c# 中的数据注释中不起作用
请提出建议。
最佳答案
根据您的要求而不是您的尝试,您需要的是:
^(?!(?:\d+|_+| +)$)[\w ]+$
否定先行查找不需要的匹配以使整个过程失败。这些是仅包含数字、仅下划线或仅包含空格的字符串。如果它们永远不会发生,我们希望匹配 ^[\w ]+$
这几乎与 ^[a-zA-Z0-9_ ]+$
相同.
解释:
^
行/字符串的开始(?!
否定先行开始(?:
非捕获组的开始\d+
匹配数字|
或者_+
匹配下划线|
或者[ ]+
匹配空格
)$
非捕获组的结尾紧跟行/字符串的结尾(不应找到之前的匹配项)
)
否定前瞻结束[\w ]+$
匹配字符集内的一个字符到输入字符串的末尾
注意:\w
是 [a-zA-Z0-9_]
的简写,除非设置了 u
修饰符。
关于c# - c# 中接受下划线和空格的字母数字字符串的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52311895/