Regular expression that allows spaces in a string,

2019-01-09 12:35发布

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 Heights, IL' would be valid, but if a user just hit the space bar any number of times and hit enter the form would not validate. Preceding the validation, I've tried running an if (foo != null) then run the regex, but hitting the space bar still registers characters, so that wasn't working. Here is what I'm using right now which allows the spaces:

^[-a-zA-Z0-9_:,.' ']{1,100}$

7条回答
Deceive 欺骗
2楼-- · 2019-01-09 12:45

Try this regular expression:

^[^\s]+(\s.*)?$

It means one or more characters that are not space, then, optionally, a space followed by anything.

查看更多
\"骚年 ilove
3楼-- · 2019-01-09 12:52

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}$
查看更多
贼婆χ
4楼-- · 2019-01-09 12:52

Just use \s* to avoid one or more blank spaces in the regular expression between two words.

For example, "Mozilla/ 4.75" and "Mozilla/4.75" both can be matched by the following regular expression:

[A-Z][a-z]*/\s*[0-9]\.[0-9]{1,2}

Adding \s* matches on zero, one or more blank spaces between two words.

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-01-09 12:56

It's very simple: .*\S.*

This requires one non-space character, at any place. The regular expression syntax is for Perl 5 compatible regular expressions, if you have another language, the syntax may differ a bit.

查看更多
Root(大扎)
6楼-- · 2019-01-09 12:59

You could use simple:

^(?=.*\S).+$

if your regex engine supports positive lookaheads. This expression requires at least one non-space character.

See it on rubular.

查看更多
Emotional °昔
7楼-- · 2019-01-09 13:03

I'm not sure you need a RegEx here. Why not just call your language's Trim() method and then ensure the resulting string is non-empty?

查看更多
登录 后发表回答