我有一个输入对话框,要求输入XML元素名称,我想检查它是否包含任何空格。
我可以像使用 name.matches() 这样做吗?
name.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"
你可以使用正则表达式“\\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 ++;
}
要检查一个字符串是否不包含任何空格,您可以使用
string.matches("^\\S*$")
例子:
"name" -> true
" " -> false
"name xxname" -> false
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
,但只是打印了大量冗余输出,而没有返回布尔值。 - Nowhere Man这已在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
}
String withSpace = "foo foo"; assert(withSpace.contains(" "));
- mel3kings