Regular expression that allows spaces in a string, but not only blank spaces

后端 未结 6 2108
长发绾君心
长发绾君心 2020-12-01 18:31

I need to write a regular expression for form validation that allows spaces within a string, but doesn\'t allow only white space.

For example - \'Chicago Heigh

6条回答
  •  醉话见心
    2020-12-01 19:18

    The following will answer your question as written, but see my additional note afterward:

    ^(?!\s*$)[-a-zA-Z0-9_:,.' ']{1,100}$
    

    Explanation: The (?!\s*$) is a negative lookahead. It means: "The following characters cannot match the subpattern \s*$." When you take the subpattern into account, it means: "The following characters can neither be an empty string, nor a string of whitespace all the way to the end. Therefore, there must be at least one non-whitespace character after this point in the string." Once you have that rule out of the way, you're free to allow spaces in your character class.

    Extra note: I don't think your ' ' is doing what you intend. It looks like you were trying to represent a space character, but regex interprets ' as a literal apostrophe. Inside a character class, ' ' would mean "match any character that is either ', a space character, or '" (notice that the second ' character is redundant). I suspect what you want is more like this:

    ^(?!\s*$)[-a-zA-Z0-9_:,.\s]{1,100}$
    

提交回复
热议问题