【问题标题】:Parsing a string that contains double quotes解析包含双引号的字符串
【发布时间】:2020-03-17 22:14:47
【问题描述】:

我有一个相对简单的 java 问题。我有一个看起来像这样的字符串:

"Anderson,T",CWS,SS

我需要以我拥有的方式解析它

Anderson,T    
CWS    
SS

全部作为单独的字符串。

谢谢!

【问题讨论】:

标签: java string parsing


【解决方案1】:

这是一个捕获带引号的字符串、删除空格和匹配空项的解决方案:

public static void main(String[] args) {
    String quoted = "\"(.*?(?<!\\\\)(?:\\\\\\\\)*)\"";
    Pattern regex = Pattern.compile(
        "(?:^|(?<=,))\\s*(" + quoted + "|[^,]*?)\\s*(?:$|,)");

    String line = "\"Anderson,T\",CWS,\"single quote\\\"\", SS ,,hello,,";
    Matcher m = regex.matcher(line);
    int count = 0;
    while (m.find()) {
        String s = m.group(2) == null ? m.group(1) : m.group(2);
        System.out.println(s);
        count++;
    }
    System.out.printf("(%d matches found)%n", count);
}

我将模式中的引用部分分开,以便更容易理解。捕获组 1 是带引号的字符串,2 是每隔一个匹配项。

分解整体格局:

  1. 查找行首或前一个逗号(?:^|(?&lt;=,))(不要捕获)
  2. 忽略 0+ 个空格 \\s*
  3. 查找带引号的字符串或不带逗号的字符串(" + quoted + "|[^,]*?) (非逗号匹配是非贪婪的,因此它不会抓取任何后续空格)
  4. 再次忽略 0+ 个空格 \\s*
  5. 查找行尾,或逗号(?:$|,)(不要捕获)

分解引用模式:

  1. 寻找开盘报价\"
  2. 开始组捕获(
  3. 获取任意字符.*?的最小匹配
  4. 匹配 0+ 偶数个反斜杠 (?&lt;!\\\\)(?:\\\\\\\\)*(以避免匹配带有或不带有前面转义反斜杠的转义引号)
  5. 关闭捕获组)
  6. 匹配结束报价\"

【讨论】:

  • 刚刚发现如果行以 , 开头,这并不总是有效 - 通过交换逗号前瞻/后向逻辑进行修复
【解决方案2】:

假设你的字符串是这样的

String input = "\"Anderson,T\",CWS,SS";

您可以使用针对类似情况找到的this 解决方案。

String input = "\"Anderson,T\",CWS,SS";
List<String> result = new ArrayList<String>();
int start = 0; //start index. Used to determine where the word starts
boolean inQuotes = false;

for (int current = 0; current < input.length(); current++) { //iterate through characters
    if (input.charAt(current) == '\"') //if found a quote
        inQuotes = !inQuotes; // toggle state
    if(current == (input.length() - 1))//if it is the last character
        result.add(input.substring(start)); //add last word
    else if (input.charAt(current) == ',' && !inQuotes) { //if found a comma not inside quotes
        result.add(input.substring(start, current)); //add everything between the start index and the current character. (add a word)
        start = current + 1; //update start index
    }
}
System.out.println(result);

我对其进行了一些修改以提高可读性。此代码将您想要的字符串存储在列表result 中。

【讨论】:

    猜你喜欢
    • 2016-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-03
    相关资源
    最近更新 更多