【发布时间】:2015-07-08 17:14:29
【问题描述】:
我正在尝试创建简单的 IDE 并基于
为我的 JTextPane 着色- 字符串 (" ")
- 评论(// 和 /* */)
- 关键字(public、int ...)
- 数字(69 等整数和 1.5 等浮点数)
我为源代码着色的方法是覆盖 StyledDocument 中的 insertString 和 removeString 方法。
经过多次测试,我已经完成了cmets和关键字。
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 中想要的。哪个是整数颜色编码的正确表达式?
下面是输出的截图:
提前感谢您的帮助!
【问题讨论】:
标签: java regex jtextpane styleddocument