我正在尝试创建简单的 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 中想要的。哪个是用于整数颜色编码的正确表达式?
下面是输出的截图:
感谢您提前提供任何帮助!