【发布时间】:2012-07-14 08:47:26
【问题描述】:
我有一个询问 XML 元素名称的输入对话框,我想检查它是否有空格。
我可以做类似 name.matches() 的事情吗?
【问题讨论】:
我有一个询问 XML 元素名称的输入对话框,我想检查它是否有空格。
我可以做类似 name.matches() 的事情吗?
【问题讨论】:
为什么要使用正则表达式?
name.contains(" ")
这应该同样有效,而且速度更快。
【讨论】:
String withSpace = "foo foo"; assert(withSpace.contains(" "));
如果您将使用正则表达式,它已经为任何非空白字符预定义了字符类“\S”。
!str.matches("\\S+")
告诉你这是否是一个至少有一个字符的字符串,其中所有字符都是非空格
【讨论】:
一个与前面类似的简单答案是:
str.matches(".*\\s.*")
将所有这些放在一起时,如果字符串中的任何位置有一个或多个空白字符,则返回 true。
这是一个简单的测试,您可以运行该测试来对您的解决方案进行基准测试:
boolean containsWhitespace(String str){
return str.matches(".*\\s.*");
}
String[] testStrings = {"test", " test", "te st", "test ", "te st",
" t e s t ", " ", "", "\ttest"};
for (String eachString : testStrings) {
System.out.println( "Does \"" + eachString + "\" contain whitespace? " +
containsWhitespace(eachString));
}
【讨论】:
string name = "Paul Creasey";
if (name.contains(" ")) {
}
【讨论】:
if (str.indexOf(' ') >= 0)
会(稍微)快一些。
【讨论】:
如果你真的想要一个正则表达式,你可以使用这个:
str.matches(".*([ \t]).*")
从某种意义上说,与此正则表达式匹配的所有内容都不是有效的 xml 标记名称:
if(str.matches(".*([ \t]).*"))
print "the input string is not valid"
【讨论】:
这是在 android 7.0 到 android 10.0 中测试的,它可以工作
使用这些代码检查字符串是否包含空格/空格可能位于第一个位置、中间或最后一个位置:
name = firstname.getText().toString(); //name is the variable that holds the string value
Pattern space = Pattern.compile("\\s+");
Matcher matcherSpace = space.matcher(name);
boolean containsSpace = matcherSpace.find();
if(constainsSpace == true){
//string contains space
}
else{
//string does not contain any space
}
【讨论】:
你可以用这段代码检查输入的字符串是否包含空格?
public static void main(String[]args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter the string...");
String s1=sc.nextLine();
int l=s1.length();
int count=0;
for(int i=0;i<l;i++)
{
char c=s1.charAt(i);
if(c==' ')
{
System.out.println("spaces are in the position of "+i);
System.out.println(count++);
}
else
{
System.out.println("no spaces are there");
}
}
【讨论】:
contains 的尝试,它只打印大量冗余输出而不是返回布尔值。
要检查字符串是否不包含任何空格,您可以使用
string.matches("^\\S*$")
例子:
"name" -> true
" " -> false
"name xxname" -> false
【讨论】:
您可以使用正则表达式“\\s”
计算空格数的示例程序(Java 9 及更高版本)
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("\\s", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("stackoverflow is a good place to get all my answers");
long matchCount = matcher.results().count();
if(matchCount > 0)
System.out.println("Match found " + matchCount + " times.");
else
System.out.println("Match not found");
}
}
对于 Java 8 及更低版本,您可以在 while 循环中使用 matcher.find() 并增加计数。例如,
int count = 0;
while (matcher.find()) {
count ++;
}
【讨论】: