我需要正则表达式来表示英文字符、连字符和下划线
例子
匹配 :
戈文德马尔维亚 govind_malviya govind123 政府
不匹配
政府马尔维亚 govind.malviya govind%马尔维亚 腕表生活 вкусно-же
试试这个:
^[A-Za-z\d_-]+$
A-Za-z
将允许字母。
\d
将允许数字。
_
将允许下划线。
-
将允许连字符。
^
分别$
代表字符串的开始和结束。
试试这个:
(?-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)»
[\w-]+
这就是你需要的。
\w
是单词字符。它与[a-zA-Z1-9_]
表示字符 from a
toz
或 from A
toZ
或 from 1
to9
或下划线相同。所以[\w-]
表示单词字符或连字符。
+
表示一次或多次