8

I am parsing a poorly structured rss feed, and some of the data that is being returned has <p>at in it. How can I replace all instance of <p>at with an empty space, using java?

I'm familiar with the .replace method for the String class, but I'm not sure how the regex expression would look. I tried inputString.replace("<p>at", "") but that didn't work.

3
  • 1
    Please show an SSCCE. The replace() doesn't use regex (and should thus just work). replaceAll() is the one which uses regex (which you should thus not use). Commented Apr 29, 2012 at 5:05
  • I meant replaceAll(). replace() woulnd't work because it takes a single character to replace. Commented Apr 29, 2012 at 5:08
  • Wow, are you still on Java 1.4 or older? Since Java 1.5 (released end of 2004), there are two replace() methods, one taking char and other taking CharSequence (and thus also String). In any way, this "typo" is precisely one of the reasons why you should show an SSCCE. So that we can in essence just copy'n'paste'n'run without changes to see your problem ourselves. Commented Apr 29, 2012 at 5:08

2 Answers 2

13

Try this:

inputString = inputString.replace("<p>at", "");

Be aware that the replace() method does not modify the String in-place (as is the case with all methods in the String class, because it's immutable), instead it returns a new String with the modifications - and you need to save the returned string somewhere.

Also, the above version of replace() doesn't receive a regular expression as an argument, just the string to be replaced and its replacement.

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

3 Comments

+1 The crucial point here is that Strings are immutable. It is impossible (well, unless you go to great lengths to fool the compiler) to change the value of a string. All methods that "change" a string will return a new string containing the modified value.
@JimGarrison spot-on!. I added that piece of information in my answer
@user1154644 if this answer was helpful for you, please don't forget to accept it.
1
inputString.replace("<p>at", "") // this will replace all match's with second parameter charsequence
inputString.replaceAll("<p>at", "") //  Replaces each substring of this string that matches the given regular expression with the given replacement.

you can use anyone.

String newInputString = inputString.replaceAll("<p>at", "");

thanks

1 Comment

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.