允许字符串中有空格的正则表达式,但不仅是空格 [英] Regular expression that allows spaces in a string, but not only blank spaces

查看:33
本文介绍了允许字符串中有空格的正则表达式,但不仅是空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为表单验证编写一个正则表达式,它允许字符串中包含空格,但不允许只包含空格.

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

例如 - 'Chicago Heights, IL' 将是有效的,但如果用户只是按任意次空格键并按回车键,则表单将无法验证.在验证之前,我尝试运行 if (foo != null) 然后运行正则表达式,但按空格键仍会注册字符,因此无法正常工作.这是我现在使用的允许空格的内容:

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}$

推荐答案

很简单:.*\S.*

这在任何地方都需要一个非空格字符.正则表达式语法适用于 Perl 5 兼容的正则表达式,如果您有其他语言,语法可能会有所不同.

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.

这篇关于允许字符串中有空格的正则表达式,但不仅是空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆