Search code examples
javajtextpane

How to get the string in the JTextPane around the caret?


For example, there is a JTextPane which has some text like "123456abcd789", and the caret is now between the '7'.

See this for explanation: "123456abcd|789". Here the '|' represents the caret.

And now I want to get the longest string before the caret which includes only a-z. Here it would be "abcd".

But if I use the method jtextpane.getCaretPosition(), I'll get an integer 11.(because there are 10 ascii chars and a picture before the caret). It isn't the integer I wanted. Maybe I can count the number of chars of the imgs, but it's still troublesome, and easy for bugs to appear.

So how to get the correct string?

EXAMPLE

<html>
    <body>
        <p>
            Hello, everybody!!<br>
            <img src="xx.jpg">
        </p>
        <p>
            Hello, everybody|!!<br>   //The caret is here, at the left of '!'
            <img src="xx.jpg">
        </p>
        <p>
            Hello, everybody!!<br>
            <img src="xx.jpg">
        </p>
    </body>
<html>

In the example above, the caret is now in the second sentence.

And what I want to do is to replace the "everybody" just before the caret into "everyone"(the rest "everybody" remain itself). But if I use getCaretPosition() I won't get the correct index of the '!' in the HTML text.

So what's the solution?


Solution

  • You can use a regular expression to count the number of characters from A to Z and a to z.

    This would be the correct expression: ([a-zA-Z]+)

    You can try more combinations using this online regex tool.


    EDIT

    Here is the regex that you can use.