如何检查输入字符串是否包含任何空格?

时间:2022-05-26 07:18:04

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

我有一个输入对话框,询问XML元素名称,我想检查它是否有任何空格。

can I do something like name.matches()?

我可以做name.matches()这样的事情吗?

5 个解决方案

#1


32  

Why use a regex?

为什么要使用正则表达式?

name.contains(" ")

That should work just as well, and be faster.

这应该同样有效,并且更快。

#2


4  

string name = "Paul Creasey";
if (name.contains(" ")) {

}

#3


4  

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

如果您将使用Regex,它已经为任何非空白字符预定义了字符类“\ S”。

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

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

告诉您这是否是至少一个字符的字符串,其中所有字符都是非空格

#4


2  

if (str.indexOf(' ') >= 0)

would be (slightly) faster.

会(稍微)更快。

#5


1  

If you really want a regex, you can use this one:

如果你真的想要一个正则表达式,你可以使用这个:

str.matches(".*([ \t]).*")

In the sense that everything matching this regex is not a valid xml tag name:

从某种意义上说,匹配此正则表达式的所有内容都不是有效的xml标记名称:

if(str.matches(".*([ \t]).*")) 
      print "the input string is not valid"

#1


32  

Why use a regex?

为什么要使用正则表达式?

name.contains(" ")

That should work just as well, and be faster.

这应该同样有效,并且更快。

#2


4  

string name = "Paul Creasey";
if (name.contains(" ")) {

}

#3


4  

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

如果您将使用Regex,它已经为任何非空白字符预定义了字符类“\ S”。

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

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

告诉您这是否是至少一个字符的字符串,其中所有字符都是非空格

#4


2  

if (str.indexOf(' ') >= 0)

would be (slightly) faster.

会(稍微)更快。

#5


1  

If you really want a regex, you can use this one:

如果你真的想要一个正则表达式,你可以使用这个:

str.matches(".*([ \t]).*")

In the sense that everything matching this regex is not a valid xml tag name:

从某种意义上说,匹配此正则表达式的所有内容都不是有效的xml标记名称:

if(str.matches(".*([ \t]).*")) 
      print "the input string is not valid"