if (subject.match(/^(?=[a-z]\w{0,7}$)/i)) {
// Successful match
}
解释:
"^" + // Assert position at the beginning of the string
"(?=" + // Assert that the regex below can be matched, starting at this position (positive lookahead)
"[a-z]" + // Match a single character in the range between “a” and “z”
"\\w" + // Match a single character that is a “word character” (letters, digits, etc.)
"{0,7}" + // Between zero and 7 times, as many times as possible, giving back as needed (greedy)
"$" + // Assert position at the end of the string (or before the line break at the end of the string, if any)
")"
And another version with lookaheads :)
if (subject.match(/^(?=[a-z]\w{0,7}$)/i)) {
// Successful match
}
Explanation :
"^" + // Assert position at the beginning of the string
"(?=" + // Assert that the regex below can be matched, starting at this position (positive lookahead)
"[a-z]" + // Match a single character in the range between “a” and “z”
"\\w" + // Match a single character that is a “word character” (letters, digits, etc.)
"{0,7}" + // Between zero and 7 times, as many times as possible, giving back as needed (greedy)
"$" + // Assert position at the end of the string (or before the line break at the end of the string, if any)
")"
发布评论
评论(5)
这可行:
例如,
This would work:
For example,
\w
简写适用于所有字母、数字和下划线。[A-Za-z]
太过分了,/i
标志将获取所有字母,不区分大小写。因此,满足您需求的超级简单正则表达式是:
/^[az]\w{0,7}$/i
The
\w
shorthand is for all letters, numbers and underscores.[A-Za-z]
is overkill, the/i
flag will get you all letters, case insensitive.Therefore, a super simple regex for what you need is:
/^[a-z]\w{0,7}$/i
试试这个:
Try this out:
试试这个:
这需要一个字母起始字符,并且可以选择允许最多 7 个字符,其中可以是字母数字或下划线。
编辑:谢谢杰西的更正。
Try this one:
This requires an alpha start character, and optionally allows up to 7 more characters which are either alphanumeric or underscore.
EDIT: Thanks, Jesse for the correction.
还有另一个带有前瞻的版本:)
解释:
And another version with lookaheads :)
Explanation :