簡體   English   中英

正則表達式為英文字符,連字符和下划線

[英]Regex for english characters, hyphen and underscore

我需要正則表達式的英文字符,連字符和下划線

比賽 :

govind-malviya
govind_malviya
govind123
govind

不匹配

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

試試這個:

^[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_] ,表示從az或從AZ或從19或下划線的字符。 所以[\\w-]表示單詞字符或連字符。
+表示一次或多次

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM