Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check whether input string contains any spaces?

Tags:

java

regex

I have a input dialog that asks for XML element name, and I want to check it to see if it has any spaces.

can I do something like name.matches()?

like image 577
Chea Indian Avatar asked Jul 15 '12 00:07

Chea Indian


People also ask

How do I check if a string contains spaces?

In order to check if a String has only unicode digits or space in Java, we use the isDigit() method and the charAt() method with decision making statements. The isDigit(int codePoint) method determines whether the specific character (Unicode codePoint) is a digit. It returns a boolean value, either true or false.

How do I check if a string contains only spaces in Python?

Python String isspace() The isspace() method returns True if there are only whitespace characters in the string. If not, it return False. Characters that are used for spacing are called whitespace characters. For example: tabs, spaces, newline, etc.


2 Answers

Why use a regex?

name.contains(" ") 

That should work just as well, and be faster.

like image 114
Kendall Frey Avatar answered Oct 05 '22 17:10

Kendall Frey


If you will use Regex, it already has a predefined character class "\S" for any non-whitespace character.

!str.matches("\\S+") 

tells you if this is a string of at least one character where all characters are non-whitespace

like image 43
Cagatay Kalan Avatar answered Oct 05 '22 18:10

Cagatay Kalan