如何在不影响CSV文件中逗号的情况下替换字符串中的逗号?

时间:2019-03-04 08:53:31

标签: java string parsing comma

我有一个要用字符串加载的数据集,它包含如下内容:

“ 10、14、15,” 20,152“,37,” 42,167“,22”

如何使用Java解析数据,以便引号内的逗号被安全删除,而其他逗号不受影响?

2 个答案:

答案 0 :(得分:1)

假设您想保留引号,则可以使用这种方法。如果没有,那么您可以对其进行一些编辑以删除引号。

public String process(String input) {
    StringBuilder result = new StringBuilder();
    boolean insideDoubleQuotes = false;
    for (char currentCharacter : input.toCharArray()) {

      if (currentCharacter == '"') {
        insideDoubleQuotes = !insideDoubleQuotes;
      } else if (currentCharacter == ',' && insideDoubleQuotes) {
        continue;
      }

      result.append(currentCharacter);
    }

    return result.toString();
  }

答案 1 :(得分:0)

尝试一下:

import java.util.ArrayList;

public class Main {

    public static void main(String args[]) {
        String input = "'10,11', '12,14', 15, '20,152', 37, '42,167', 22"; //
        String[] list = input.split("'"); // Split the string using "'" as delimeter(change it to quotation mark)
        ArrayList<String> elements = new ArrayList<>();
        for (int i = 0; i < list.length; i++) {
                        // condition to check if it is outside/outside the quotation mark
            if (i % 2 != 0) {  // if inside a quotation mark
                if (!list[i].trim().isEmpty()) { // so that spaces will not be included
                    elements.add(list[i].trim()); // add the element to the list
                }
            } else { //if outside the quotation marks
                String[] tmp = list[i].split(","); // split the regular comma separated values
                for (String s : tmp) { // iterate each splits
                    if (!s.trim().isEmpty()) { // check for spaces
                        elements.add(s.trim()); // add element to the list
                    }
                }
            }
        }

        for (String s : elements) {
            System.out.println(s);
        }
    }

}