Repository navigation
Expand file tree
/
Copy pathFaqFile.java
More file actions
38 lines (33 loc) · 1.45 KB
/
Copy pathFaqFile.java
File metadata and controls
38 lines (33 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.regex.Pattern;
/**
* Reads and writes the "question=answer" lines in faq.txt. A '=' or '\' inside a
* question is saved with a backslash in front so it can't be mistaken for the
* separator; lines saved before this change have no backslashes and load the same.
*/
final class FaqFile {
// The codes a terminal sends for keys like the arrows, e.g. ESC [ A.
private static final Pattern ESCAPE_SEQUENCE = Pattern.compile("\\x1B(\\[[0-9;?]*[ -/]*[@-~]|O.)");
private FaqFile() {}
static String formatLine(String question, String answer) {
return question.replace("\\", "\\\\").replace("=", "\\=") + "=" + answer;
}
/** Returns {question, answer}, or null when the line has no separator. */
static String[] parseLine(String line) {
StringBuilder question = new StringBuilder();
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (c == '\\' && i + 1 < line.length()) {
question.append(line.charAt(++i));
} else if (c == '=') {
return new String[] { question.toString(), line.substring(i + 1) };
} else {
question.append(c);
}
}
return null;
}
/** Removes key escape codes and other control characters, then trims. */
static String clean(String text) {
return ESCAPE_SEQUENCE.matcher(text).replaceAll("").replaceAll("\\p{Cntrl}", "").trim();
}
}