仅允许大写/小写(字母字符)、句点、空格和破折号的正则表达式是什么? [英] What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?
问题描述
我在创建正则表达式验证器时遇到问题,该验证器会检查以确保输入仅包含大写或小写字母字符、空格、句点、下划线和破折号.无法通过搜索在线找到此示例.例如:
I am having problems creating a regex validator that checks to make sure the input has uppercase or lowercase alphabetical characters, spaces, periods, underscores, and dashes only. Couldn't find this example online via searches. For example:
这些没问题:
Dr. Marshall
sam smith
.george con-stanza .great
peter.
josh_stinson
smith _.gorne
任何包含其他字符的东西都是不行的.那是数字或任何其他符号.
Anything containing other characters is not okay. That is numbers, or any other symbols.
推荐答案
您要查找的正则表达式是 ^[A-Za-z.\s_-]+$
The regex you're looking for is ^[A-Za-z.\s_-]+$
^
断言正则表达式必须匹配主题的开头[]
是一个字符类 - 允许在此表达式中匹配的任何字符A-Z
允许大写字符范围a-z
允许小写字符范围.
匹配句点而不是一系列字符\s
匹配空白(空格和制表符)_
匹配下划线-
匹配破折号(连字符);我们将它作为字符类中的最后一个字符,因此它不会被解释为字符范围的一部分.我们也可以转义它 (\-
) 并将其放在字符类中的任何位置,但这不太清楚+
断言前面的表达式(在我们的例子中是字符类)必须匹配一次或多次$
最后,这断言我们现在处于主题的结尾
^
asserts that the regular expression must match at the beginning of the subject[]
is a character class - any character that matches inside this expression is allowedA-Z
allows a range of uppercase charactersa-z
allows a range of lowercase characters.
matches a period rather than a range of characters\s
matches whitespace (spaces and tabs)_
matches an underscore-
matches a dash (hyphen); we have it as the last character in the character class so it doesn't get interpreted as being part of a character range. We could also escape it (\-
) instead and put it anywhere in the character class, but that's less clear+
asserts that the preceding expression (in our case, the character class) must match one or more times$
Finally, this asserts that we're now at the end of the subject
在测试正则表达式时,您可能会发现 regexpal 之类的工具很有帮助.这使您可以在编写示例数据时实时查看正则表达式匹配(或不匹配)示例数据.
When you're testing regular expressions, you'll likely find a tool like regexpal helpful. This allows you to see your regular expression match (or fail to match) your sample data in real time as you write it.
这篇关于仅允许大写/小写(字母字符)、句点、空格和破折号的正则表达式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!