0

I have these tags in my textarea

<gras>.....</gras>

And I'm trying to replace them using the replaceAll() String method

text.replaceAll("<gras>", "<b>");

text.replaceAll("</gras>", "</b>");

But, this regex code doesn't work. Any help please ?

7
  • What exactly are you trying to replace? Just the open tag? Open and close tags? Open and close tags and all the content within? Commented Aug 30, 2013 at 15:51
  • 2
    "doesn't work" is pretty vague. What happens? And why are you using replaceAll (which uses regular expressions) instead of replace? Commented Aug 30, 2013 at 15:51
  • Try to escape the operands with \< and \>. Commented Aug 30, 2013 at 15:52
  • 3
    Are you assigning the return value to anything? Remember that Strings are immutable in Java, and it returns the modified value instead of modifying the argument in-place. Commented Aug 30, 2013 at 15:52
  • Can you show your full code ? Commented Aug 30, 2013 at 15:52

2 Answers 2

5

You forgot a very important concept;

. Change text.replaceAll("<gras>", "Bold!");

To

text = text.replaceAll("<gras>", "Bold!");

Assign text = some Function, as text.replace() is creating a new String object and not referencing it.

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

2

Strings don't replace. Strings construct new Strings with the replacement values.

Also, if you are dealing with XML, regex is the wrong tool. That doesn't mean it can't work, and it might be useful in some limited examples, but it shouldn't be the first tool to use. Much like a hammer shouldn't be the first tool to use when installing a screw.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.