Reputation: 13753
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 腕錶生活 вкусно-же
Upvotes: 16
Views: 26049
Reputation: 11182
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)»
Upvotes: 2
Reputation: 3333
try this out:
^[A-Za-z\d_-]+$
A-Za-z
would allow alphabets.
\d
would allow numbers.
_
would allow underscore.
-
would allow hyphen.
^
and $
represent the start and end of string respectively.
Upvotes: 29
Reputation: 11958
[\w-]+
this is what you need.
\w
is word character. 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. So [\w-]
means a word character or a hyphen.
+
means one or more times
Upvotes: -2