2

I am creating a simple IDE to color my JTextPane according to source code. Currently, I am able to match:

  • Comments (// & /* */)
  • Strings (" ")
  • Numbers (Integers & Decimals)
  • Keywords (e.g. public / protected ..)

Q1: I would like to include char coloring the same way as strings. For example: char c = 'a';

Am i supposed to change my string regular expression to cater for char detection too?

After much testing, I detected a scenario that will mess up my String detection coloring is when a user enters char c = ' " '; The 2nd string that gets detected will detect it as part of the 1st string (Example shown below.

My string coloring messes up my whole IDE coloring :(

This is how i detect string patterns and set color to it:

Pattern strings = Pattern.compile("\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"");
Matcher matcherS = strings.matcher(text);
while (matcherS.find())
    setCharacterAttributes(matcherS.start(), matcherS.end() - matcherS.start(), red, false);

Below is a sample output from my IDE:

enter image description here

Q2: Am i supposed to edit my String detection regex to solve this error?

Thanks in advance.

In case anyone finds in helpful, I got my String IDE detection regex from:

Which is the right regular expression to use for Numbers and Strings?

Community
  • 1
  • 1
user3188291
  • 567
  • 1
  • 9
  • 22
  • If i can attain both char and string coloring just through 1 regex matching that would be the most ideal situation. – user3188291 Jul 10 '15 at 04:21
  • 1
    Pay attention to bullet number 4: http://blog.codinghorror.com/regular-expressions-now-you-have-two-problems/ – Nir Alfasi Jul 10 '15 at 04:28

2 Answers2

1

This should work:

Pattern stringPattern = Pattern.compile("((?<!\\\\)\\\"(.*?)\\\"(?<!\\\\\\\"))");

See: https://regex101.com/r/kT4oZ1/1

griFlo
  • 2,084
  • 18
  • 28
0

Why not use a ready made library for that like below:
https://github.com/bobbylight/RSyntaxTextArea

Ali Helmy
  • 784
  • 6
  • 18