Is there a cleaner way to parse delimited strings if it has only one element?

I have a String. This line has comma separated values ​​(e.g. Bob, John, Jill), but sometimes this line has only one value (e.g. Bob). I need to extract these values, so I'm using something like this:

String str = "Bob,John,Jill";
StringTokenizer strTok = new StringTokenizer(str , ",");

This works, and now I have access to 3 names separately., But what if my line contains only the word Bob (now there is no comma). This code fails, so my solution is to check for a comma, and if that happens, I tocanize, if not, then I just get the line (I know this condition is not good because it does not handle null and other conditions properly, but I just want this not to show the problem):

if( (str != null) && (!str.isEmpty()) && (!str.contains(",")) && (str.length() > 0)){
    // only 1 element exists, just use the string
}
else{
    //Tokenize
}

, , , ? , , - , ?

+4
1

StringTokenizer:

StringTokenizer - , , . , , , split String java.util.regex.

Guava Splitter . String.split() ( JDK ), -.


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
}

( ), , .

+6

Source: https://habr.com/ru/post/1615136/


All Articles