What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?

后端 未结 2 975
半阙折子戏
半阙折子戏 2020-12-30 20:22

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 dash

相关标签:
2条回答
  • 2020-12-30 20:32

    The regex you're looking for is ^[A-Za-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 allowed
    • A-Z allows a range of uppercase characters
    • a-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

    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.

    0 讨论(0)
  • 2020-12-30 20:44

    Check out the basics of regular expressions in a tutorial. All it requires is two anchors and a repeated character class:

    ^[a-zA-Z ._-]*$
    

    If you use the case-insensitive modifier, you can shorten this to

    ^[a-z ._-]*$
    

    Note that the space is significant (it is just a character like any other).

    0 讨论(0)
提交回复
热议问题