我正在尝试创建简单的 IDE 并根据以下内容为我的 JTextPane 着色
- 字符串(“”)
- 注释(// 和 /* */)
- 关键字(公共、int ...)
- 数字(整数,如 69,浮点数,如 1.5)
我为源代码着色的方式是覆盖 StyledDocument 中的 insertString 和 removeString 方法。
经过多次测试,我已经完成了评论和关键字。
Q1:对于我的字符串着色,我根据以下正则表达式为字符串着色:
Pattern strings = Pattern.compile("\"[^\"]*\"");
Matcher matcherS = strings.matcher(text);
while (matcherS.find()) {
setCharacterAttributes(matcherS.start(), matcherS.end() - matcherS.start(), red, false);
}
这在 99% 的情况下都有效,除非我的字符串包含特定类型的字符串,其中代码内有一个“\”。这会弄乱我的整个颜色编码。
任何人都可以更正我的正则表达式来修复我的错误吗?
Q2:对于整数和小数着色,根据以下正则表达式检测数字:
Pattern numbers = Pattern.compile("\\d+");
Matcher matcherN = numbers.matcher(text);
while (matcherN.find()) {
setCharacterAttributes(matcherN.start(), matcherN.end() - matcherN.start(), magenta, false);
}
通过使用正则表达式“\d+”,我只处理整数而不处理浮点数。另外,作为另一个字符串一部分的整数会被匹配,这不是我在 IDE 中想要的。用于整数颜色编码的正确表达式是什么?
Below is a screenshot of the output:
感谢您提前提供的任何帮助!