REGEX (javascript) - 允许带有不在第一个位置的特殊字符的字母数字字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11976901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
REGEX (javascript) - Allow alphanumeric characters with special characters not in the first position
提问by Adam Levitt
I'd like to devise a regex expression that allows alphanumeric characters, as well as other characters as long as they're not in the first position. Examples:
我想设计一个正则表达式,允许字母数字字符以及其他字符,只要它们不在第一个位置。例子:
VALID: Test
VALID: Hello123
VALID: 456 Hi
VALID: 456-789
VALID: Hi-777
VALID: 333-Hi
VALID: Hello-There
VALID: What's Up
VALID: Hello#Goodbye
INVALID: -Hello
INVALID: &Goodbye
Here's my starting point, which only allows alphanumeric:
这是我的起点,它只允许字母数字:
/[a-zA-Z]+/
回答by Michael Berkowski
Use ^[A-Za-z0-9]
to require an alphnum character in the first position (immediately following ^
, the start of the string), followed by whatever else you need.
用于^[A-Za-z0-9]
在第一个位置(紧接在^
,字符串的开头)中要求一个字母字符,然后是您需要的任何其他字符。
# Specific set permitted -- add all the characters you need...
/^[A-Za-z0-9][A-Za-z-9, +-_&#'"]+$/
# Or anything permitted after the first position
# Use .* instead of .+ if a single character string is permissible.
/^[A-Za-z0-9].+$/
回答by Oussama
Try this regular expression :
试试这个正则表达式:
/^[a-zA-Z0-9].*$/
回答by John Dvorak
/^\w/
if you only need to test, /^\w.*$/
, if you need the entire string to be matched as well.
If you allow the empty string as well, you can use /^(\w|$)/
, read as the string begins with a word character or with its end (is empty), or /^(\w.*)?$/
, read as the string is a word character followed by anything, once or not at all.
/^\w/
如果您只需要测试,/^\w.*$/
,如果您还需要匹配整个字符串。如果您也允许使用空字符串,则可以使用/^(\w|$)/
, read as 该字符串以单词字符开头或结尾(为空),或/^(\w.*)?$/
, read as the string is a word character后跟任何内容,一次或根本不.