我正在嘗試將輸入字串決議為標記,其中每個標記都是字串中的一個單詞。但是,我也希望標記能夠包含空格,并且為了更清晰的語法,我希望能夠讓引號出現在標記的中間,并且能夠轉義引號 ( \")
示例輸入字串和我想要的輸出(從輸出中洗掉引號以表示字串以提高可讀性):
- 輸入:
diamond_sword name:"test name"-> 輸出:[diamond_sword, name:test name] - 輸入:
stick 1 name:"The \"Holy\" Stick"-> 輸出:[stick, 1, name:The "Holy" Stick]
而不是做什么很多人都問在以前的問題,我不希望引號必須從其他字(獨立name:"string"),我只想逃出報價維持,洗掉所有未轉義的引號。
這可能嗎?以這種方式將字串轉換為串列會是什么樣子?
uj5u.com熱心網友回復:
也許是這樣的?
import java.util.*;
public class Demo {
private static List<String> parse(String in) {
Objects.requireNonNull(in);
char[] chars = in.toCharArray();
var words = new ArrayList<String>();
var sb = new StringBuilder();
for (int i = 0; i < chars.length; i ) {
if (chars[i] == ' ') {
// Space; add the current token to the result array.
words.add(sb.toString());
sb.setLength(0);
} else if (chars[i] == '"') {
// Iterate until the next unescaped quote
// (Assumes strings are well-formatted; a more robust version
// wouldn't and would better handle error cases)
for (i ; chars[i] != '"'; i ) {
// If current character is a backslash, skip and append
// the next
if (chars[i] == '\\') {
i ;
}
sb.append(chars[i]);
}
} else {
sb.append(chars[i]);
}
}
words.add(sb.toString()); // Don't forget the final token
return words;
}
public static void main(String[] args) {
List<String> strings =
List.of("diamond_sword name:\"test name\"",
"stick 1 name:\"The \\\"Holy\\\" Stick\"");
for (String s : strings) {
List<String> words = parse(s);
System.out.println(words);
}
}
}
編譯并運行時,列印出來
[diamond_sword, name:test name]
[stick, 1, name:The "Holy" Stick]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/404645.html
標籤:
下一篇:與Twig的字串連接
