正则表达式为英文字符,连字符和下划线

时间:2013-02-02 06:23:32

标签: c# regex

我需要Regex用于英文字符,连字符和下划线

示例

匹配:

govind-malviya
govind_malviya
govind123
govind

不匹配

govind malviya
govind.malviya
govind%malviya
腕錶生活
вкусно-же

3 个答案:

答案 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_]相同,表示从az或从AZ或从1到{{1}的字符或者下划线。所以9表示单词字符或连字符 [\w-]表示一次或多次