最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - How can I validate white space? - Stack Overflow

programmeradmin4浏览0评论

I have to validate a String with only white spaces. In my String white spaces between a String is allowed but only white spaces not allowed. For example "conditions apply","conditions" etc is allowed but not " ". ie, only white space not allowed

I want a regular expression in JavaScript for this

I have to validate a String with only white spaces. In my String white spaces between a String is allowed but only white spaces not allowed. For example "conditions apply","conditions" etc is allowed but not " ". ie, only white space not allowed

I want a regular expression in JavaScript for this

Share Improve this question edited Jan 7, 2013 at 14:03 RP89 asked Jan 7, 2013 at 12:36 RP89RP89 1412 gold badges5 silver badges16 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 7

Try this regular expression

".*\\S+.*"

Do you really need to use a regex?

if (str.trim().length() == 0)
    return false;
else
    return true;

As mentionned in the ments, this could be simplified to a one-liner

return str.trim().length() > 0;

or, since Java 6

return !str.trim().isEmpty();

you can do it like this:

// This does replace all whitespaces at the end of the string
String s = "      ".trim();
if(s.equals(""))
    System.out.println(true);
else 
    System.out.println(s);

what about checking if the string does not match "\\s+"?

The regular expression is ^\\s*$ is used to match a whitespace only string, you can validate against this.

^     # Match the start of the string 
\\s*  # Match zero of more whitespace characters
$     # Match the end of the string

Anchoring to the start and the end of the string is important here.

发布评论

评论列表(0)

  1. 暂无评论