I try to split
"11020199,Abc Germany ,aduz,,444,bieb,dc,2 ,2222.00,whatever 5dc,222.22,22.00,""98,00"",""12,00"",21-09-2018,06:00 "
It has double quotation only when theres a comma in the string, otherwise its seperated by just the comma and theres no double quotation.
How do i split this line properly? I've seen how to split it when everything is double quotated but not when its only done when theres a comma.
A simple example solution could be this, which takes care of the comma in double quoted values being kept:
Split the String by comma first and use the double quotes in order to merge their values afterwards:
public class SplitAndKeepQuotedValuesCommas {
public static void main(String[] args) {
String source = "11020199,Abc Germany ,aduz,,444,bieb,dc,2 ,2222.00,whatever 5dc,222.22,22.00,\"\"98,00\"\",\"\"12,00\"\",21-09-2018,06:00";
// split the String by comma
String[] justValues = source.split(",");
// print all items in the result
for (String s : justValues) {
System.out.println(s);
}
// prepare a List for all the values
List<String> resultList = new ArrayList<String>();
// then go through the values
for (int i = 0; i < justValues.length; i++) {
// and check if there is a String that begins with double double quotes
if (justValues[i].startsWith("\"\"")) {
/*
* if there is one, remove the double quotes from it and its successor,
* then concatenate them with a comma in between and add the result to the list
*/
String merged = justValues[i].replace("\"\"", "") + "," + justValues[i + 1].replace("\"\"", "");
resultList.add(merged);
/*
* since there are still values with trailing double double quotes,
* only add values without because they have already been added inside the merged value
*/
} else if (!justValues[i].endsWith("\"\"")) {
resultList.add(justValues[i]);
}
}
resultList.forEach(value -> {
System.out.println(value);
});
}
}
Interesting problem. Here a possible solution (although I'm not really happy with it myself..)
String str = "11020199,Abc Germany ,aduz,,444,bieb,dc,2 ,2222.00,whatever 5dc,222.22,22.00,\"\"98,00\"\",\"\"12,00\"\",21-09-2018,06:00";
// Replace the comma between double quotes with a replacement char you're sure isn't in the String:
// TODO: Use a more suitable character, I don't know what your text can/cannot contain
String modifiedStr = str.replaceAll("(\"\"[^,]+),([^,]+\"\")", "$1🍺$2");
// Now split by comma:
String[] array = modifiedStr.split(",");
// And then change the replacement char back again to a comma:
for(int i=0; i<array.length; i++)
array[i] = array[i].replace("🍺", ",");
Try it online.
NOTE: Assumes the values between double double-quotes will only contain a single comma.
If nothing else works you have to do it step by step. Check what comes next (comma or double quotes) and cut the next word.
public static String[] split(String s) {
List<String> l = new ArrayList<>();
int begin = 0;
while (begin < s.length()) {
int nextQuotes = s.indexOf("\"\"", begin);
if (nextQuotes == begin) {
l.add(s.substring(begin + 2, s.indexOf("\"\"", begin + 2)));
begin = s.indexOf("\"\"", begin + 2) + 2;
continue;
}
int nextComma = s.indexOf(',', begin);
if (nextComma == begin) {
l.add("");
begin++;
continue;
} else if (nextComma == -1) {
l.add(s.substring(begin));
begin = s.length();
continue;
}
l.add(s.substring(begin, nextComma));
begin = nextComma + 1;
}
return l.toArray(new String[] {});
}
Not the best solution but it works.
You can do it as below [You can improve extracting some part to some method, but this will work for you anyway]
String[] splittedData = s.split(",");
List<String> data = new ArrayList<>(splittedData.length);
StringBuilder sb = new StringBuilder();
for (String splittedDataPart : splittedData) {
splittedDataPart = splittedDataPart.trim();
if (sb.length() == 0 && !splittedDataPart.startsWith("\"")) {
data.add(splittedDataPart);
continue;
}
if (sb.length() != 0)
sb.append(",");
sb.append(splittedDataPart.replace("\"", ""));
if (splittedDataPart.endsWith("\"")) {
data.add(sb.toString());
sb.setLength(0);//clearing
}
}
Related
I'm trying to make an encryptor.What i want it to do:
Get the text i enter and reverse the first two letters of every word
and then display it again.
I have tried a lot of ways.This is the last one i've tried:
private void TranslateToEf(){
String storage = Display.getText();
String[] arr = storage.split("\\W+");
for ( String ss : arr) {
char c[] = ss.toCharArray();
char temp = c[0];
c[0] = c[1];
c[1] = temp;
String swappedString = new String(c);
Display.appendText(swappedString + " ");
}
}
You may want to consider maintaining all the delimiters lost from the first String.split("\\W+") so they can be included in the final result. I would do that with a String.split("\\w+")
You may also want to consider that when you swap the first two letters, if the first letter is capital it becomes lowercase and the second letter becomes uppercase. Otherwise, just do a direct swap.
Code sample:
public static void main(String[] args) throws Exception {
String data = "Hello;World! My name is John. I write code.";
String[] words = data.split("\\W+");
String[] delimiters = data.split("\\w+");
int delimiterIndex = 0;
StringBuilder sb = new StringBuilder();
for (String word : words) {
if (word.length() < 2) {
sb.append(word);
} else {
char firstLetter = word.charAt(0);
char secondLetter = word.charAt(1);
if (Character.isUpperCase(firstLetter)) {
// Swap the first two letters and change casing
sb.append(Character.toUpperCase(secondLetter))
.append(Character.toLowerCase(firstLetter));
} else {
// Swap the first two letters
sb.append(secondLetter)
.append(firstLetter);
}
// Append the rest of the word past the first two letters
sb.append(word.substring(2));
}
// Append delimiters
if (delimiterIndex < delimiters.length) {
// Skip blank delimiters if there are any
while (delimiters[delimiterIndex].isEmpty()) {
delimiterIndex++;
}
// Append delimiter
sb.append(delimiters[delimiterIndex++]);
}
}
data = sb.toString();
// Display result
System.out.println(data);
}
Results:
Ehllo;Owrld! Ym anme si Ojhn. I rwite ocde.
public class Encrypto {
public static void main(String[] args) {
String input="Hello World";
String [] word = input.split(" ");
// System.out.println(word[0]);
String encryWord="";
for(int i=0;i<word.length;i++){
if (word[i].length() > 0) {
String tmp0 = String.valueOf(word[i].charAt(1));
String tmp1 = String.valueOf(word[i].charAt(0));
encryWord += tmp0.toLowerCase() + tmp1.toLowerCase() + word[i].substring(2) + " ";
}else{
encryWord +=word[i];
}
}
System.out.println(encryWord);
}
}
I think answer is more helpful for you
There are a few problems.
Declare zz outside the loop if you want to use it outside.
Append zz on every iteration. Not just assign it.
Something like this,
private void TranslateToEf(){
String storage = Display.getText();
String[] arr = storage.split("\\W+");
String zz = "";
for ( String ss : arr) {
char c[] = ss.toCharArray();
char temp = c[0];
c[0] = c[1];
c[1] = temp;
String swappedString = new String(c);
String b= " ";
zz += swappedString + b;
}
Display.setText(zz + " ");
}
You are splitting with non-word (\W+) characters, but replacing it only with a space " ". This could alter the string with special characters.
Not sure what exactly you are looking for but i little modification in your code see if this suits your needs
String storage = "Test test t";
String[] arr = storage.split("\\W+");
String abc = "";
for ( String ss : arr) {
if(ss.length() > 1)
{
char c[] = ss.toCharArray();
char temp = c[0];
c[0] = c[1];
c[1] = temp;
String swappedString = new String( c );
String b = " ";
String zz = swappedString + b;
abc = abc + zz;
}else{
abc = abc + ss;
}
}
System.out.println(abc);
In Java strings are immutable. You can't modify them "on the fly", you need to reassign them to a new instance.
Additionally, you are setting the last display text to zz, but zz is a local variable to your loop, and therefore it gets re-instantiated with every iteration. In other words, you would be assigning to display only the last word!
Here is what you have to do to make it work:
String storage = Display.getText();
String[] arr = storage.split("\\W+");
String[] newText = new String[arr.length];
for ( int i = 0; i<arr.length; i++) {
String original = arr[i];
String modified = ((char) original.charAt(1)) + ((char) original.charAt(0)) + original.substring(2);
newText[i] = modified;
}
//Join with spaces
String modifiedText = Arrays.asList(newText).stream().collect(Collectors.join(" "));
Display.setText(modifiedText);
Note that:
1) We are assuming all strings have at least 2 chars
2) that your splitting logic is correct. Can you think some edge cases where your regexp fails?
I have a text file which contain many lines, every line contain many words separated by delimiter like "hello,world,I,am,here".
I want to extract some words between position and delimiter for example:
the position is 7 so the string is "world" and if the position was 1 the string will be "hello"
I would recommend using the split() method. With commas delimiting the words you would do this:
String[] words = "hello,world,I,am,here".split(",");
Then you can get the words by position by indexing into the array:
words[3] // would yield "am"
Note that the parameter to split() is a regular expression, so if you aren't familiar with them see the docs here (or google for a tutorial).
Just implement the following code while taking advantage of the method split() that can be used an all Strings objects :
String line = "hello,world,I,am,here";
String[] words = line.split(",");
public static String wordAtPosition(String line, int position) {
String[] words = line.split(",");
int index = 0;
for (String word : words) {
index += word.length();
if (position < index) {
return word;
}
}
return null;
}
Example
String line = "hello,world,I,am,here";
String word = wordAtPosition(line, 7);
System.out.println(word); // prints "world"
First get the substring , then split and get first element from Array.
public class Test {
public static void main(String[] args) throws ParseException {
Test test = new Test();
String t = test.getStringFromLocation("hello,world,I,am,here", 1, ",");
System.out.println(t);
t = test.getStringFromLocation("hello,world,I,am,here", 7, ",");
System.out.println(t);
t = test.getStringFromLocation("hello,world,I,am,here", 6, ",");
System.out.println(t);
}
public String getStringFromLocation(final String input, int position,
String demlimter) {
if (position == 0) {
return null;
}
int absoulutionPosition = position - 1;
String[] value = input.substring(absoulutionPosition).split(demlimter);
return value.length > 0 ? value[0] : null;
}
}
Not the most readable solution but covers corner cases. The split solutions are nice but does not reflect the position in the original string since it skips the ',' from the count
String line = "hello,world,I,am,here";
int position = new Random().nextInt(line.length());
int startOfWord = -1;
int currentComa = line.indexOf(",", 0);
while (currentComa >= 0 && currentComa < position) {
startOfWord = currentComa;
currentComa = line.indexOf(",", currentComa + 1);
}
int endOfWord = line.indexOf(",", position);
if(endOfWord < 0) {
endOfWord = line.length();
}
String word = line.substring(startOfWord + 1, endOfWord);
System.out.println("position " + position + ", word " + word);
Converting it to char array and then concatenating it back replacing spaces with "%20".
OR
Dividing string into substrings with "white space" as the "separator" and just combining the strings with "%20" between them.
For eg:
Str = "This is John Shaw "
(There are as many extra spaces at the end as there are spaces in the string)
expected outcome:
"This%20is%20John%20Shaw"
Is it not this ?
txt = txt.replaceAll(" ", "%20");
Let me know if I understood it wrong.
By replaceAll method of the String class as follow.
String str = "This is John Shaw ";
str = str.replaceAll(" ", "%20");
Output
This%20is%20John%20Shaw%20
You can write both algorithms with a complexity O(n) where n is the number of characters in the String but there are much better algorithms to do that.
By the way I wrote an example that show you the computing time, one method is faster than the other but they are both, as I said, O(n)
public class ComplexityTester
{
//FIRST METHOD
public static String replaceSpacesArray(String str)
{
str = str.trim(); // leading and trailing whitespaces omitted
char[] charArray = str.toCharArray();
String result = "";
for(int i = 0; i<charArray.length; i++) // it replaces spaces with %20
{
if(charArray[i] == ' ') //it's a space, replace it!
result += "%20";
else //it's not a space, add it!
result += charArray[i];
}
return result;
}
//SECOND METHOD
public static String replaceSpacesWithSubstrings(String str)
{
str = str.trim(); // leading and trailing whitespaces omitted
String[] words = new String[5]; //array of strings, to add substrings
int wordsSize = 0; //strings in the array
//From the string to an array of substrings
//(the words separated by spaces of the string)
int indexFrom = 0;
int indexTo = 1;
while(indexTo<=str.length())
{
if(wordsSize == words.length) //if the array is full, resize it!
words = resize(words);
//we reach the end of the sting, add the last word to the array!
if(indexTo == str.length())
{
words[wordsSize++] = str.substring(indexFrom, indexTo++);
}
else if(str.substring(indexTo-1,indexTo).equals(" "))//it's a space
{
//we add the last word to the array
words[wordsSize++] = str.substring(indexFrom, indexTo-1);
indexFrom = indexTo; //update the indices
indexTo++;
}
else //it's a character not equal to space
{
indexTo++; //update the index
}
}
String result = "";
// From the array to the result string
for(int i = 0; i<wordsSize; i++)
{
result += words[i];
if(i+1!=wordsSize)
result += "%20";
}
return result;
}
private static String[] resize(String[] array)
{
int newLength = array.length*2;
String[] newArray = new String[newLength];
System.arraycopy(array,0,newArray,0,array.length);
return newArray;
}
public static void main(String[] args)
{
String example = "The Java Tutorials are practical guides "
+"for programmers who want to use the Java programming "
+"language to create applications. They include hundreds "
+"of complete, working examples, and dozens of lessons. "
+"Groups of related lessons are organized into \"trails\"";
String testString = "";
for(int i = 0; i<100; i++) //String 'testString' is string 'example' repeted 100 times
{
testString+=example;
}
long time = System.currentTimeMillis();
replaceSpacesArray(testString);
System.out.println("COMPUTING TIME (ARRAY METHOD) = "
+ (System.currentTimeMillis()-time));
time = System.currentTimeMillis();
replaceSpacesWithSubstrings(testString);
System.out.println("COMPUTING TIME (SUBSTRINGS METHOD) = "
+ (System.currentTimeMillis()-time));
}
}
Well, this is my first time get here.
I'm trying to figure out the correct way to replace number into letter.
In this case, I need two steps.
First, convert letter to number. Second, restore number to word.
Words list: a = 1, b = 2, f = 6 and k = 11.
I have word: "b a f k"
So, for first step, it must be: "2 1 6 11"
Number "2 1 6 11" must be converted to "b a f k".
But, I failed at second step.
Code I've tried:
public class str_number {
public static void main(String[] args){
String word = "b a f k";
String number = word.replace("a", "1").replace("b","2").replace("f","6").replace("k","11");
System.out.println(word);
System.out.println(number);
System.out.println();
String text = number.replace("1", "a").replace("2","b").replace("6","f").replace("11","k");
System.out.println(number);
System.out.println(text);
}
}
Result:
b a f k
2 1 6 11
2 1 6 11
b a f aa
11 must be a word "k", but it's converted to "aa"
What is the right way to fix this?
Or do you have any other ways to convert letter to number and vice versa?
Thank you.
It would be good to write methods for conversion between number and letter format. I would write some code like this and use it generally instead of hard coding replace each time.
public class test {
static ArrayList <String> letter = new ArrayList<String> ();
static ArrayList <String> digit = new ArrayList<String> ();
public static void main(String[] args) {
createTable();
String test="b a f k";
String test1="2 1 6 11";
System.out.println(letterToDigit(test));
System.out.println(digitToLetter(test1));
}
public static void createTable()
{
//Create all your Letter to number Mapping here.
//Add all the letters and digits
letter.add("a");
digit.add("1");
letter.add("b");
digit.add("2");
letter.add("c");
digit.add("3");
letter.add("d");
digit.add("4");
letter.add("e");
digit.add("5");
letter.add("f");
digit.add("6");
letter.add("g");
digit.add("7");
letter.add("h");
digit.add("8");
letter.add("i");
digit.add("9");
letter.add("j");
digit.add("10");
letter.add("k");
digit.add("11");
letter.add("l");
digit.add("12");
letter.add("m");
digit.add("13");
letter.add("n");
digit.add("14");
letter.add("o");
digit.add("14");
letter.add("p");
digit.add("15");
//Carry so on till Z
}
public static String letterToDigit(String input)
{
String[] individual = input.split(" ");
String result="";
for(int i=0;i<individual.length;i++){
if(letter.contains(individual[i])){
result+=Integer.toString(letter.indexOf(individual[i])+1)+ " ";
}
}
return result;
}
public static String digitToLetter(String input)
{
String[] individual = input.split(" ");
String result="";
for(int i=0;i<individual.length;i++){
if(digit.contains(individual[i])){
result+=letter.get(digit.indexOf(individual[i])) + " ";
}
}
return result;
}
}
I would actually not use replace in this case.
A more generic solution would be to simply convert it to a char and subtract the char a from it.
int n = word.charAt(0) - 'a' + 1;
This should return an int with the value you are looking for.
If you want this to be an string you can easily do
String s = Integer.parseInt(word.charAt(0) - 'a' + 1);
And as in your case you are doing a whole string looping through the length of it and changing all would give you the result
String s = "";
for(int i = 0; i < word.length(); i++) {
if(s.charAt(i) != ' ') {
s = s + Integer.toString(word.charAt(i) - 'a' + 1) + " ";
}
}
and then if you want this back to an String with letters instead
String text = "";
int temp = 0;
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == ' ') {
text = text + String.valueOf((char) (temp + 'a' - 1));
temp = 0;
} else if {
temp = (temp*10)+Character.getNumericValue(s.charAt(i));
}
}
You can just reverse the replacement:
String text = number.replace("11","k").replace("2","b").replace("6","f").replace("1","a");
Simplest solution IMO.
When adding other numbers, first replace these with two digits, then these with one.
Replace this:
String text = number.replace("1", "a").replace("2","b").replace("6","f").replace("11","k");
By this:
String text = number.replace("11","k").replace("1", "a").replace("2","b").replace("6","f");
Right now, the first replace you're doing: ("1", "a")
is invalidating the last one: ("11","k")
I think you would need to store the number as an array of ints. Otherwise, there is no way of knowing if 11 is aa or k. I would create a Map and then loop over the characters in the String. You could have one map for char-to-int and one for int-to-char.
Map<Character,Integer> charToIntMap = new HashMap<Character,Integer>();
charToIntMap.put('a',1);
charToIntMap.put('b',2);
charToIntMap.put('f',6);
charToIntMap.put('k',11);
Map<Integer,Character> intToCharMap = new HashMap<Integer,Character>();
intToCharMap.put(1,'a');
intToCharMap.put(2,'b');
intToCharMap.put(6,'f');
intToCharMap.put(11,'k');
String testStr = "abfk";
int[] nbrs = new int[testStr.length()];
for(int i = 0; i< testStr.length(); i++ ){
nbrs[i] = charToIntMap.get(testStr.charAt(i));
}
StringBuilder sb = new StringBuilder();
for(int num : nbrs){
sb.append(num);
}
System.out.println(sb.toString());
//Reverse
sb = new StringBuilder();
for(int i=0; i<nbrs.length; i++){
sb.append(intToCharMap.get(nbrs[i]));
}
System.out.println(sb.toString());
This failed because the replace("1", "a") replaced both 1s with a characters. The quickest fix is to perform the replace of all the double-digit numbers first, so there are no more double-digit numbers left when the single-digit numbers get replaced.
String text = number.replace("11","k").replace("1", "a").
replace("2","b").replace("6","f");
I would like to do a java split via regex.
I would like to split my string on every comma when it is NOT in single quotes or brackets.
example:
Hello, 'my,',friend,(how ,are, you),(,)
should give:
hello
my,
friend
how, are, you
,
I tried this:
(?i),(?=([^\'|\(]*\'|\([^\'|\(]*\'|\()*[^\'|\)]*$)
But I can't get it to work (I tested via http://java-regex-tester.appspot.com/)
Any ideas?
Nested paranthesises can't be split by regex. Its easier to split them manually.
public static List<String> split(String orig) {
List<String> splitted = new ArrayList<String>();
int nextingLevel = 0;
StringBuilder result = new StringBuilder();
for (char c : orig.toCharArray()) {
if (c == ',' && nextingLevel == 0) {
splitted.add(result.toString());
result.setLength(0);// clean buffer
} else {
if (c == '(')
nextingLevel++;
if (c == ')')
nextingLevel--;
result.append(c);
}
}
// Thanks PoeHah for pointing it out. This adds the last element to it.
splitted.add(result.toString());
return splitted;
}
Hope this helps.
A java CSV parser library would be better suited to this task than regex: http://sourceforge.net/projects/javacsv/
Assuming no nested (), you could split on
",(?=(?:[^']*'[^']*')*[^']*$)(?=(?:[^()]*\\([^()]*\\))*[^()]*$)"
It will only split on a comma when ahead in the string is an even number of ' and bracket pairs.
It's a brittle solution, but it may be good enough.
As in some comments and answer by #Balthus this should better be done in a CSV Parser. You do need to do some smart RexEx replacement to prepare the input string for parsing. Consider code like this:
String str = "Hello, 'my,',friend,(how ,are, you),(,)"; // input string
// prepare String for CSV parser: replace left/right brackets OR ' by a "
CsvReader reader = CsvReader.parse(str.replaceAll("[(')]", "\""));
reader.readRecord(); // read the CSV input
for (int i=0; i<reader.getColumnCount(); i++)
System.out.printf("col[%d]: [%s]%n", i, reader.get(i));
OUTPUT
col[0]: [Hello]
col[1]: [my,]
col[2]: [friend]
col[3]: [how ,are, you]
col[4]: [,]
I also need to split on comma outside of quotes and brackets.
After searching over all the related answers on SO, I realized a lexer is needed in such a case, and I wrote a generic implementation for myself. It supports a separator, multiple quotes and multiple brackets as regexes.
public static List<String> split(String string, String regex, String[] quotesRegex, String[] leftBracketsRegex,
String[] rightBracketsRegex) {
if (leftBracketsRegex.length != rightBracketsRegex.length) {
throw new IllegalArgumentException("Bracket count mismatch, left: " + leftBracketsRegex.length + ", right: "
+ rightBracketsRegex.length);
}
// Prepare all delimiters.
String[] delimiters = new String[1 + quotesRegex.length + leftBracketsRegex.length + rightBracketsRegex.length];
delimiters[0] = regex;
System.arraycopy(quotesRegex, 0, delimiters, 1, quotesRegex.length);
System.arraycopy(leftBracketsRegex, 0, delimiters, 1 + quotesRegex.length, leftBracketsRegex.length);
System.arraycopy(rightBracketsRegex, 0, delimiters, 1 + quotesRegex.length + leftBracketsRegex.length,
rightBracketsRegex.length);
// Build delimiter regex.
StringBuilder delimitersRegexBuilder = new StringBuilder("(?:");
boolean first = true;
for (String delimiter : delimiters) {
if (delimiter.endsWith("\\") && !delimiter.endsWith("\\\\")) {
throw new IllegalArgumentException("Delimiter contains trailing single \\: " + delimiter);
}
if (first) {
first = false;
} else {
delimitersRegexBuilder.append("|");
}
delimitersRegexBuilder
.append("(")
.append(delimiter)
.append(")");
}
delimitersRegexBuilder.append(")");
String delimitersRegex = delimitersRegexBuilder.toString();
// Scan.
int pendingQuoteIndex = -1;
Deque<Integer> bracketStack = new LinkedList<>();
StringBuilder pendingSegmentBuilder = new StringBuilder();
List<String> segmentList = new ArrayList<>();
Matcher matcher = Pattern.compile(delimitersRegex).matcher(string);
int matcherIndex = 0;
while (matcher.find()) {
pendingSegmentBuilder.append(string.substring(matcherIndex, matcher.start()));
int delimiterIndex = -1;
for (int i = 1; i <= matcher.groupCount(); ++i) {
if (matcher.group(i) != null) {
delimiterIndex = i - 1;
break;
}
}
if (delimiterIndex < 1) {
// Regex.
if (pendingQuoteIndex == -1 && bracketStack.isEmpty()) {
segmentList.add(pendingSegmentBuilder.toString());
pendingSegmentBuilder.setLength(0);
} else {
pendingSegmentBuilder.append(matcher.group());
}
} else {
delimiterIndex -= 1;
pendingSegmentBuilder.append(matcher.group());
if (delimiterIndex < quotesRegex.length) {
// Quote.
if (pendingQuoteIndex == -1) {
pendingQuoteIndex = delimiterIndex;
} else if (pendingQuoteIndex == delimiterIndex) {
pendingQuoteIndex = -1;
}
// Ignore unpaired quotes.
} else if (pendingQuoteIndex == -1) {
delimiterIndex -= quotesRegex.length;
if (delimiterIndex < leftBracketsRegex.length) {
// Left bracket
bracketStack.push(delimiterIndex);
} else {
delimiterIndex -= leftBracketsRegex.length;
// Right bracket
int topBracket = bracketStack.peek();
// Ignore unbalanced brackets.
if (delimiterIndex == topBracket) {
bracketStack.pop();
}
}
}
}
matcherIndex = matcher.end();
}
pendingSegmentBuilder.append(string.substring(matcherIndex, string.length()));
segmentList.add(pendingSegmentBuilder.toString());
while (segmentList.size() > 0 && segmentList.get(segmentList.size() - 1).isEmpty()) {
segmentList.remove(segmentList.size() - 1);
}
return segmentList;
}