If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Substring replacement on AttributedString

How can I replace a substring of an AttributedString with another string of characters? I have an application that allows the user to input text into a JTextPane and the text is then stored as an AttributedString. I'd like them to be able to type in something like "My name is %NAME%" and then be able to replace the characters %NAME% with a string from a database. I've been trying to use regular expressions to do this but the problem is that I need to be able to retain the character formatting. I can strip all the character attributes off and get String containing the characters of the AttributedString and then use a regx to replace the substring but then I have to put the attributes back on which is especially difficult if the length of the two substrings is different. i.e. %NAME% is 6 characters, Bob is 3. Any suggestions?

This is an interesting problem. The CharacterIterator/AttributedCharacterIterator methods just do not seem to offer any assistance - all about the attributes but nothing about the associated text.

Based on what I have seen in my limited review of this, I think I would just create a new AttributedString if I had to modify the text. The Iterator methods are good enough to allow me to specifically set attributes based on the location of the name in the string.

I can iterate over the AttributedString a character at a time to put the values into a new AttributedString but the problem is that the Iterator only processes 1 character at a time. I can't figure out how to determine if what it's processing is like %NAME% and not just a lone % (as in 30%). The other thing I was considering was using a regx (or something) to find the indexes of the characters I want to replace and splitting the string into pieces, storing them in an array, processing each relevant element in the array and then pieceing it all back together.
Example:

can't you determine the length of the "new" substring - and that is the number of loops you need to do for your substitution ... you already know the index of the start and end of the reserved area ... then delete anything from the original if the reserved area is longer than the new substring ... and just add stuff if you reach the end of the reserved area and still have new substring left unadded ...

all substitution in a string works this way - the String class actually uses a Stringbuilder object since string objects are immutable - just most of the time it is going on under the covers ... here's your peek underneath ...