我的任务是检测服务器应用程序的 csv 中是否存在任何字符串空格。 CSV的内容是日语、英语、一些符号和数字的组合。 英语中的空格是半角,日语中的空格是全角。两种语言中空格的宽度和字节大小不同。
我正在使用 Java 8 进行编码,最好不要使用第 3 方库。
我正在考虑两种方法,这些是伪代码。
正则表达式:
targetStr.matches("\\s+");
Character.isWhitespace():
targetStr.codepoints()
.filter(c -> Character.isWhitespace(c))
.count() > 0
上述伪代码中的任何一个都可以完成该任务吗?
哪一个对我的情况更有效?
最佳答案
首先,targetStr.matches("\\s+")
和targetStr.codepoints().filter(c -> Character.isWhitespace(c)).count() > 0
有着完全不同的逻辑。
String.matches
需要整个字符串匹配,因此 \s+
它必须完全由空白组成。相比之下,count() > 0
如果您至少有一个空白字符,则满足,因此这是 targetStr.codepoints().anyMatch(Character::isWhitespace)
的低效且冗长的版本。 .
如果你想检查所有字符是否都是空格,你应该使用 allMatch
相反。
但进一步来说,空白有不同的定义
Determines if the specified character (Unicode code point) is white space according to Java. A character is a Java whitespace character if and only if it satisfies one of the following criteria:
- It is a Unicode space character (
SPACE_SEPARATOR
,LINE_SEPARATOR
, orPARAGRAPH_SEPARATOR
) but is not also a non-breaking space ('\u00A0'
,'\u2007'
,'\u202F'
).- It is
'\t'
, U+0009 HORIZONTAL TABULATION.- It is
'\n'
, U+000A LINE FEED.- It is
'\u000B'
, U+000B VERTICAL TABULATION.- It is
'\f'
, U+000C FORM FEED.- It is
'\r'
, U+000D CARRIAGE RETURN.- It is
'\u001C'
, U+001C FILE SEPARATOR.- It is
'\u001D'
, U+001D GROUP SEPARATOR.- It is
'\u001E'
, U+001E RECORD SEPARATOR.- It is
'\u001F'
, U+001F UNIT SEPARATOR.
the \s
pattern (默认):
\s
A whitespace character:[ \t\n\x0B\f\r]
所以存在显着差异。
如 this answer 中所述,你可以做\s
匹配所有空白字符或使用首先匹配所有 unicode 空白字符的模式。或者引用Character.isWhitespace
同样的逻辑明确地,这并不完全相同:
如果你想严格应用Character.isWhitespace
的逻辑,您可以使用
- 匹配所有个字符
-
string.codePoints().allMatch(Character::isWhitespace)
-
string.matches("\\p{javaWhitespace}+")
-
string.isBlank()
(JDK11)
-
- 当有至少一个空白字符时进行匹配
-
string.codePoints().anyMatch(Character::isWhitespace)
-
string.matches(".*\\p{javaWhitespace}.*")
-
Pattern.compile("\\p{javaWhitespace}").matcher(string).find()
-
作为Character.isWhitespace
的第一个项目符号文档指出,它将返回 false
对于不间断空格字符( '\u00A0'
、 '\u2007'
、 '\u202F'
),尽管它们具有空白 Unicode 属性。如果你想将它们匹配为空白,你可以使用
- 匹配所有个字符
-
string.matches("(?U)\\s+")
-
string.matches("\\p{IsWhiteSpace}+")
-
- 当有至少一个空白字符时进行匹配
-
string.matches("(?U).*\\s.*")
-
string.matches(".*\\p{IsWhiteSpace}.*")
-
Pattern.compile("\\p{IsWhitespace}").matcher(string).find()
-
Pattern.compile("\\s", Pattern.UNICODE_CHARACTER_CLASS).matcher(string).find()
-
关于java - 检测全角和半角的空白 : regex VS Character. isWhitespace(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57996089/