我正在通过重用已发布的代码here来实现语法突出显示。问题是每个字符“{,},<,>”没有颜色它没有跟随非char。例如在“
@Override
public void insertString (int offset, String str, AttributeSet a) throws BadLocationException
{
super.insertString(offset, str, a);
String text = getText(0, getLength());
int before = findLastNonWordChar(text, offset);
if (before < 0) before = 0;
int after = findFirstNonWordChar(text, offset + str.length());
int wordL = before;
int wordR = before;
while (wordR <= after) {
if (wordR == after || String.valueOf(text.charAt(wordR)).matches("\\W")) {
if (text.substring(wordL, wordR).matches("(\\W)*(SELECT|WHERE)"))
setCharacterAttributes(wordL, wordR - wordL, attr, false);
else if (text.substring(wordL, wordR).matches("(\\W)*(\\{|\\}|\\<|\\>)"))
setCharacterAttributes(wordL, wordR - wordL, attrRed, false);
else
setCharacterAttributes(wordL, wordR - wordL, attrBlack, false);
wordL = wordR;
}
wordR++;
}
}
private int findLastNonWordChar (String text, int index) {
while (--index >= 0) {
if (String.valueOf(text.charAt(index)).matches("\\W")) {
break;
}
}
return index;
}
private int findFirstNonWordChar (String text, int index) {
while (index < text.length()) {
if (String.valueOf(text.charAt(index)).matches("\\W")) {
break;
}
index++;
}
return index;
}
答案 0 :(得分:0)
要匹配Java 8正则表达式中的尖括号,必须使用
.*
所以使用:
.matches("<.*")
匹配单个尖括号。将它与你已经拥有的正则表达式结合起来得到一个尖括号,没有双反斜杠(\)。