Skip to content

Commit fb08514

Browse files
committed
StringUtils: add splitUnquoted method
This lets you split on a separator string but ignore instances of it inside of quotations ("). Does not support escaped quotes.
1 parent c95856f commit fb08514

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/main/java/org/scijava/util/StringUtils.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@
6363

6464
import java.io.File;
6565
import java.text.DecimalFormatSymbols;
66+
import java.util.regex.Pattern;
6667

6768
/**
6869
* Useful methods for working with {@link String}s.
@@ -80,6 +81,16 @@ private StringUtils() {
8081
// NB: prevent instantiation of utility class.
8182
}
8283

84+
/**
85+
* Splits a string only at separators outside of quotation marks ({@code "}).
86+
* Does not handle escaped quotes.
87+
*/
88+
public static String[] splitUnquoted(final String s, final String separator) {
89+
// See https://stackoverflow.com/a/1757107/1919049
90+
return s.split(Pattern.quote(separator) +
91+
"(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
92+
}
93+
8394
/** Normalizes the decimal separator for the user's locale. */
8495
public static String sanitizeDouble(String value) {
8596
value = value.replaceAll("[^0-9,\\.]", "");

src/test/java/org/scijava/util/StringUtilsTest.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232

3333
package org.scijava.util;
3434

35+
import static org.junit.Assert.assertArrayEquals;
3536
import static org.junit.Assert.assertEquals;
3637
import static org.junit.Assert.assertFalse;
3738
import static org.junit.Assert.assertNotNull;
@@ -47,6 +48,21 @@
4748
*/
4849
public class StringUtilsTest {
4950

51+
/** Tests {@link StringUtils#splitUnquoted}. */
52+
@Test
53+
public void testSplitUnquoted() {
54+
// See https://stackoverflow.com/a/1757107/1919049
55+
final String line = "foo,bar,c;qual=\"baz,blurb\",d;junk=\"quux,syzygy\"";
56+
final String[] expected = {
57+
"foo",
58+
"bar",
59+
"c;qual=\"baz,blurb\"",
60+
"d;junk=\"quux,syzygy\""
61+
};
62+
final String[] actual = StringUtils.splitUnquoted(line, ",");
63+
assertArrayEquals(expected, actual);
64+
}
65+
5066
@Test
5167
public void isNullOrEmptyFalseIfString() throws Exception {
5268
assertFalse(StringUtils.isNullOrEmpty("Fresh out of Red Leicester"));

0 commit comments

Comments
 (0)