如果它只有一项,是否有 "cleaner" 方法来解析分隔的字符串?
Is there a "cleaner" way to parse a deliminated string if it only has one item?
我有一个字符串。此字符串具有由逗号分隔的值(例如 Bob、John、Jill),但有时此字符串将只有一个值(例如 Bob)。
我需要提取这些值,所以我使用这样的东西:
String str = "Bob,John,Jill";
StringTokenizer strTok = new StringTokenizer(str , ",");
这行得通,我现在可以分别访问 3 个名字。但是,如果我的字符串只包含单词 Bob(现在没有逗号)怎么办?这段代码失败了,所以我的解决方案是检查逗号是否存在,如果存在,则我将其标记化,如果不存在,则我只获取字符串(我知道这个条件语句不好,因为它没有正确处理 null 和其他条件,但我只是想保持简短以显示问题):
if( (str != null) && (!str.isEmpty()) && (!str.contains(",")) && (str.length() > 0)){
// only 1 element exists, just use the string
}
else{
//Tokenize
}
这对我来说似乎不是一个非常干净的解决方案,有没有更好的方法可以避免这样的条件检查?我尝试使用正则表达式,但无法找到一个解决方案来说明是否只有一个元素或我可以使用的某些第三方库?
不要使用 StringTokenizer
:
StringTokenizer
is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split
method of String
or the java.util.regex
package instead.
你应该使用 Guava Splitter
instead. You could just use String.split()
(which is the JDK's suggested alternative), but it's less powerful and has confusing trailing-delimiter handling.
出于教育目的,以下是如何使用 Pattern
完成相同的工作(但同样,只需使用 Splitter
):
// Matches up to the next comma or the end of the line
Pattern CSV_PATTERN = Pattern.compile("(?<=,|^)([^,]*)(,|$)");
List<String> ls = new ArrayList<String>();
Matcher m = CSV_PATTERN.matcher(input);
while (m.find()) {
ls.add(m.group(1).trim()); // .trim() is optional
}
正则表达式向后查找逗号或字符串的开头(以避免字符串末尾的零宽度匹配),后跟零个或多个非逗号字符,后跟逗号或行尾。
我有一个字符串。此字符串具有由逗号分隔的值(例如 Bob、John、Jill),但有时此字符串将只有一个值(例如 Bob)。 我需要提取这些值,所以我使用这样的东西:
String str = "Bob,John,Jill";
StringTokenizer strTok = new StringTokenizer(str , ",");
这行得通,我现在可以分别访问 3 个名字。但是,如果我的字符串只包含单词 Bob(现在没有逗号)怎么办?这段代码失败了,所以我的解决方案是检查逗号是否存在,如果存在,则我将其标记化,如果不存在,则我只获取字符串(我知道这个条件语句不好,因为它没有正确处理 null 和其他条件,但我只是想保持简短以显示问题):
if( (str != null) && (!str.isEmpty()) && (!str.contains(",")) && (str.length() > 0)){
// only 1 element exists, just use the string
}
else{
//Tokenize
}
这对我来说似乎不是一个非常干净的解决方案,有没有更好的方法可以避免这样的条件检查?我尝试使用正则表达式,但无法找到一个解决方案来说明是否只有一个元素或我可以使用的某些第三方库?
不要使用 StringTokenizer
:
StringTokenizer
is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use thesplit
method ofString
or thejava.util.regex
package instead.
你应该使用 Guava Splitter
instead. You could just use String.split()
(which is the JDK's suggested alternative), but it's less powerful and has confusing trailing-delimiter handling.
出于教育目的,以下是如何使用 Pattern
完成相同的工作(但同样,只需使用 Splitter
):
// Matches up to the next comma or the end of the line
Pattern CSV_PATTERN = Pattern.compile("(?<=,|^)([^,]*)(,|$)");
List<String> ls = new ArrayList<String>();
Matcher m = CSV_PATTERN.matcher(input);
while (m.find()) {
ls.add(m.group(1).trim()); // .trim() is optional
}
正则表达式向后查找逗号或字符串的开头(以避免字符串末尾的零宽度匹配),后跟零个或多个非逗号字符,后跟逗号或行尾。