[ "word1", "key=\"value with space\-6ren">
gpt4 book ai didi

Java 在单词中间用引号分隔字符串

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:56:05 24 4
gpt4 key购买 nike

我非常感谢 Java 代码的一些帮助来拆分以下输入:

word1 key="value with space" word3 -> [ "word1", "key=\"value with space\"", "word3" ]
word1 "word2 with space" word3 -> [ "word1", "word2 with space", "word3" ]
word1 word2 word3 -> [ "word1" , "word2", "word3" ]

第一个样本输入是困难的。第二个单词在字符串中间而不是开头有引号。我找到了几种处理中间示例的方法,如 Split string on spaces in Java, except if between quotes (i.e. treat \"hello world\" as one token) 中所述。

最佳答案

而不是完全使用正则表达式,您可以对字符串进行简单的迭代:

public static String[] splitWords(String str) {
List<String> array = new ArrayList<>();
boolean inQuote = false; // Marker telling us if we are between quotes
int previousStart = -1; // The index of the beginning of the last word
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (Character.isWhitespace(c)) {
if (previousStart != -1 && !inQuote) {
// end of word
array.add(str.substring(previousStart, i));
previousStart = -1;
}
} else {
// possibly new word
if (previousStart == -1) previousStart = i;
// toggle state of quote
if (c == '"')
inQuote = !inQuote;
}
}
// Add last segment if there is one
if (previousStart != -1)
array.add(str.substring(previousStart));
return array.toArray(new String [array.size()]);
}

此方法的优点是能够根据需要多次正确识别远离空格的引号。例如,以下是单个字符串:

a"b c"d"e f"g

关于Java 在单词中间用引号分隔字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34645418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com