正则表达式仅用于字母,短划线和空格

时间:2014-05-27 16:13:14

标签: javascript jquery regex

我觉得自己很傻,但是我正在考虑这个愚蠢的小东西。

我有这个正则表达式只接受字母表字符。

我需要它也接受破折号和空格。

var letters = /^[A-Za-z]+$/;

请解释一下做什么,这个正则表达式非常令人困惑:@

干杯!

3 个答案:

答案 0 :(得分:1)

var letters = /^[A-Za-z -]+$/;

并解释一下:

/          Begin Regexp
^          Matches the start of a line
[          Begins a character group, matches anything in the group
    A-Z    Any letter between capital A and Z inclusive.
    a-z    Any letter between lower case a and z inclusive.
    " "    A space
    -      A litteral hyphen
]          Ends character group
+          Matches one or more of the previous thing(the character group)
$          Matches the end of the line
/          Ends regexp

答案 1 :(得分:1)

var lettersDashesAndSpaces = /^[A-Za-z -]+$/;
// beginning of line ─────────┘│        │││
// any of... ──────────────────┴────────┘││
// ...letters A-Z and a-z                ││
// ...space                              ││
// ...dash                               ││
// one or more of the "any of" items ────┘│
// end of line ───────────────────────────┘

诀窍是构造[...]定义了一个"字符类",意思是"方括号和#34之间列出的任何字符;但是,您还可以包含范围(例如A-Z,意思是"' A'' Z')之间的任何字母。

您只需要添加"空格"和"连字符"字符类的字符。最后的连字符让正则表达式引擎知道你没有定义一个范围,而是想要一个字面连字符。

另见regexper.com

enter image description here

答案 2 :(得分:0)

试试这个:

var lettersSpacesDashes = /^[a-z -]+$/i;

查看实际操作:http://www.regexr.com/38tff