如何检查Java字符串是否不是所有空格? [英] How do I check that a Java String is not all whitespaces?

查看:525
本文介绍了如何检查Java字符串是否不是所有空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Java检查Java字符串或字符数组是否仅由空格组成?

I want to check that Java String or character array is not just made up of whitespaces, using Java?

这是一个非常类似的问题,除了它的Javascript:

This is a very similar question except it's Javascript:
How can I check if string contains characters & whitespace, not just whitespace?

EDIT :我删除了有关字母数字字符的内容,因此更有意义.

EDIT: I removed the bit about alphanumeric characters, so it makes more sense.

推荐答案

我能想到的最短的解决方案:

Shortest solution I can think of:

if (string.trim().length() > 0) ...

这仅检查(非)空白.如果要检查特定的字符类,则需要使用强大的match()和正则表达式,例如:

This only checks for (non) white space. If you want to check for particular character classes, you need to use the mighty match() with a regexp such as:

if (string.matches(".*\\w.*")) ...

...这将检查至少一个(ASCII)字母数字字符.

...which checks for at least one (ASCII) alphanumeric character.

这篇关于如何检查Java字符串是否不是所有空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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