我的以下程序打印了我不明白的奇怪结果,我想这是由于我对 Java Regex 缺乏深入的了解。所以我希望首先按句点拆分 testStr
,然后检查每个句子是否包含字母或数字。但令人惊讶的是,我得到了以下输出,这与我的愿望相反:
blah blah1 is not a character!
blah blah2 is not a character!
blah blah3 is not a character!
??** is not a character! // only this output is expected
我的代码如下:
String testStr = "blah blah1. blah blah2. blah blah3. ??**...";
String[] myStrArray = testStr.split("[.]");
System.out.println("length of myStrArray is: " + myStrArray.length);
for (String str : myStrArray) {
if (!Pattern.matches("\\w+", str)) {
System.out.println(str + " is not a character!");
continue;
}
System.out.println("got a meaningful sentence " + str.trim());
}
最佳答案
您的程序使用点作为分隔符分割字符串,因此您得到:
blah blah1
blah blah2
blah blah3
??**...
然后您尝试使用正则表达式 \w+
来匹配每一行。请注意调用match()
相当于调用find()
但使用包含 ^
的正则表达式和$
,即认为您的正则表达式是 ^\w+$
。
我认为现在很明显您的任何一个字符串都不匹配此模式,因为前 3 个字符串包含空格,最后一个字符串既不包含字母字符也不包含数字。
关于Java 正则表达式 : check if a sentence contains only alphabet and numbers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25956448/