如何拆分字符串包含JAVA中的双引号和转义双引号?

问题描述 投票:0回答:1

假设我有一个输入字符串"Tim \"Apple\"" "Mark \"FB\"" "Elon \"Cars\""

我想基于引用块(而不是转义引用块)将该字符串拆分为String数组。结果应如下所示:

[Tim "Apple", Mark "FB", Elon "cars"]

我该怎么做才能得到这个结果?非常感谢。

java string split double-quotes
1个回答
0
投票

像这样:

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Re {
        public static List<String> parse(String s) {
                Matcher m = Pattern.compile("\"([^\\\\\"]|\\\\.)+\"") // Match from one quote to the next non-escaped one
                        .matcher(s);
                List<String> matches = new ArrayList<>();
                while(m.find()) {
                        String match = m.group();
                        match = match.substring(1, match.length() - 1); // Remove the quotes from the beginning and end
                        match = match.replaceAll("\\\\(.)", "$1"); // Remove all escapes, without accidentally removing escaped backslashes
                        matches.add(match);
                }
                return matches;
        }

        public static void main(String[] args) {
                System.out.println(args[0]);
                System.out.println(parse(args[0]));
        }
}

结果:

"Tim \"Apple\"" "Mark \"FB\"" "Elon \"Cars\""
[Tim "Apple", Mark "FB", Elon "Cars"]
© www.soinside.com 2019 - 2024. All rights reserved.