我需要Regex用于英文字符,连字符和下划线
示例
匹配:
govind-malviya govind_malviya govind123 govind
不匹配
govind malviya govind.malviya govind%malviya 腕錶生活 вкусно-же
答案 0 :(得分:23)
试试这个:
^[A-Za-z\d_-]+$
A-Za-z
会允许使用字母
\d
会允许数字
_
允许使用下划线
-
允许连字符。
^
和$
分别代表字符串的开头和结尾。
答案 1 :(得分:1)
试试这个:
(?-i)^[a-z0-9_-]+$(?#case sensitive, matches only lower a-z)
或
(?i)^[a-z0-9_-]+$(?#case insensitive, matches lower and upper letters)
示例代码
try {
Regex regexObj = new Regex("^[a-z0-9_-]+$(?#case sensitive, matches only lower a-z)", RegexOptions.Multiline);
Match matchResults = regexObj.Match(subjectString);
while (matchResults.Success) {
for (int i = 1; i < matchResults.Groups.Count; i++) {
Group groupObj = matchResults.Groups[i];
if (groupObj.Success) {
// matched text: groupObj.Value
// match start: groupObj.Index
// match length: groupObj.Length
}
}
matchResults = matchResults.NextMatch();
}
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
正则表达式解剖
// (?-i)^[a-z0-9_-]+$(?#case sensitive, matches only lower a-z)
//
// Options: ^ and $ match at line breaks
//
// Match the remainder of the regex with the options: case sensitive (-i) «(?-i)»
// Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
// Match a single character present in the list below «[a-z0-9_-]+»
// Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
// A character in the range between “a” and “z” «a-z»
// A character in the range between “0” and “9” «0-9»
// The character “_” «_»
// The character “-” «-»
// Assert position at the end of a line (at the end of the string or before a line break character) «$»
// Comment: case sensitive, matches only lower a-z «(?#case sensitive, matches only lower a-z)»
答案 2 :(得分:-2)
[\w-]+
这就是你所需要的
\w
是单词字符。它与[a-zA-Z1-9_]
相同,表示从a
到z
或从A
到Z
或从1
到{{1}的字符或者下划线。所以9
表示单词字符或连字符
[\w-]
表示一次或多次