简体   繁体   English

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

[英]Regex for english characters, hyphen and underscore

I need Regex for english characters, hyphen and underscore 我需要正则表达式的英文字符,连字符和下划线

Example

Match : 比赛 :

govind-malviya
govind_malviya
govind123
govind

Not Match 不匹配

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

try this out: 试试这个:

^[A-Za-z\d_-]+$

A-Za-z would allow alphabets. A-Za-z允许使用字母表。
\\d would allow numbers. \\d会允许数字。
_ would allow underscore. _将允许下划线。
- would allow hyphen. -会允许连字符。 ^ and $ represent the start and end of string respectively. ^$代表字符串的开头和结尾。

Try this: 试试这个:

(?-i)^[a-z0-9_-]+$(?#case sensitive, matches only lower a-z)

or 要么

(?i)^[a-z0-9_-]+$(?#case insensitive, matches lower and upper letters)

sample code 示例代码

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
}

regex anatomy 正则表达式解剖学

// (?-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-]+ this is what you need. [\\w-]+这就是你需要的。
\\w is word character. \\w是单词字符。 it's the same as [a-zA-Z1-9_] which means a character from a to z or from A to Z or from 1 to 9 or underscore. 它与[a-zA-Z1-9_] ,表示从az或从AZ或从19或下划线的字符。 So [\\w-] means a word character or a hyphen. 所以[\\w-]表示单词字符或连字符。
+ means one or more times +表示一次或多次

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM