Html 正则表达式 - 仅第一个字符检查非字母字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19821572/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 15:06:47  来源:igfitidea点击:

Regular Expression - Only first character check non-letter characters

javascripthtmlregex

提问by A. Mesut Konuklar

I've started to study on javascript and regexp specially. I am trying to improve myself on generating regular expressions.

我已经开始专门研究 javascript 和 regexp。我正在努力提高自己生成正则表达式的能力。

What I am trying to do is - I have a name field in my html file (its in a form ofc)

我想要做的是 - 我的 html 文件中有一个 name 字段(它的形式为 ofc)

...
    <label for="txtName">Your Name*: </label>
    <input id="txtName" type="text" name="txtName" size="30" maxlength="40">
...

And in my js file I am trying to check name cannot start with any NON-letter character, only for the first character. And whole field cannoth contain any special character other than dash and space.

在我的 js 文件中,我试图检查名称不能以任何非字母字符开头,仅适用于第一个字符。并且整个字段不能包含除破折号和空格之外的任何特殊字符。

They cannot start with any non-letter character ;

它们不能以任何非字母字符开头;

/^[A-Z a-z][A-Z a-z 0-9]*$/

They cannot contain any symbol other than dash and space ;

它们不能包含除破折号和空格之外的任何符号;

/^*[[&-._].*]{1,}$/

When I am testing if it works, it doesn't work at all. In which part am I failing ?

当我测试它是否有效时,它根本不起作用。我在哪部分失败了?

回答by Trenton Trama

Try /^[A-Za-z][A-Za-z0-9 -]*$/
When you include a space in the character listing ([]), it's going to be allowed in the string that's being searched.

尝试/^[A-Za-z][A-Za-z0-9 -]*$/
在字符列表 ( []) 中包含空格时,将允许在正在搜索的字符串中使用空格。

^[A-Za-z]matches the first character and says that it must be a letter of some sort.
[A-Za-z0-9 -]*$will match any remaining characters(if they exist) after the first character and make sure it's alpha numeric, or contains spaces or dashes.

^[A-Za-z]匹配第一个字符并说它必须是某种字母。
[A-Za-z0-9 -]*$将匹配第一个字符之后的任何剩余字符(如果存在),并确保它是字母数字,或者包含空格或破折号。